// SettingsPanel.jsx v3
// v6.6: Tilføjer "Vis i tabel" sektion med separate table_visible_metrics

const BRANDS_LIST = [
  { id: 'simply', label: 'Simply' },
  { id: 'dandomain', label: 'Dandomain' },
  { id: 'curanet', label: 'Curanet' },
  { id: 'scannet', label: 'Scannet' },
];

const STANDARD_EVENTS = [
  { value: 'purchase', label: 'Purchase' },
  { value: 'add_to_cart', label: 'Add to cart' },
  { value: 'initiate_checkout', label: 'Initiate checkout' },
  { value: 'lead', label: 'Lead' },
  { value: 'complete_registration', label: 'Complete registration' },
  { value: 'subscribe', label: 'Subscribe' },
  { value: 'submit_application', label: 'Submit application' },
  { value: 'contact', label: 'Contact' },
  { value: 'landing_page_view', label: 'Landing page view' },
  { value: 'view_content', label: 'View content' },
];

const DEFAULT_VISIBLE_METRICS = ['spend', 'impressions', 'link_clicks', 'link_ctr', 'cpc_link', 'cpm', 'frequency', 'reach'];

const SettingsPanel = ({ open, onClose, onPresetChange }) => {
  const [allPresets, setAllPresets] = React.useState([]);
  const [activePresetId, setActivePresetId] = React.useState(null);
  const [config, setConfig] = React.useState({});
  const [selectedBrand, setSelectedBrand] = React.useState('simply');
  const [conversions, setConversions] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [savedFlash, setSavedFlash] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [activeSection, setActiveSection] = React.useState('events');

  const METRIC_DEFINITIONS = window.AppMetrics?.METRIC_DEFINITIONS || [];

  const loadPresets = async () => {
    try {
      const r = await fetch('/api/presets');
      const data = await r.json();
      setAllPresets(data.presets || []);
      const active = data.presets.find(p => p.is_active === 1);
      if (active) {
        setActivePresetId(active.id);
        setConfig(JSON.parse(active.config_json));
      }
      setLoading(false);
    } catch (err) {
      setError(String(err));
      setLoading(false);
    }
  };

  React.useEffect(() => { if (open) loadPresets(); }, [open]);

  React.useEffect(() => {
    if (!open) return;
    fetch(`/api/conversions/${selectedBrand}`)
      .then(r => r.json())
      .then(data => setConversions(data.conversions || []))
      .catch(() => setConversions([]));
  }, [selectedBrand, open]);

  const activePreset = allPresets.find(p => p.id === activePresetId);
  const isDefault = activePreset?.is_default === 1;
  const brandConfig = config[selectedBrand] || {
    primary_events: [],
    primary_event_labels: {},
    thresholds: {},
    visible_metrics: [...DEFAULT_VISIBLE_METRICS],
    table_visible_metrics: [],  // v6.6: separat konfiguration for tabel
    threshold_metrics: [],
    advanced_events: [],
  };

  if (brandConfig.primary_event && !brandConfig.primary_events) {
    brandConfig.primary_events = [brandConfig.primary_event];
    brandConfig.primary_event_labels = brandConfig.primary_event_labels || {};
    if (brandConfig.primary_event_label) {
      brandConfig.primary_event_labels[brandConfig.primary_event] = brandConfig.primary_event_label;
    }
  }

  const updateBrandConfig = (updates) => {
    setConfig({ ...config, [selectedBrand]: { ...brandConfig, ...updates } });
  };

  const toggleEvent = (eventKey, label) => {
    const list = brandConfig.primary_events || [];
    const labels = { ...brandConfig.primary_event_labels };
    if (list.includes(eventKey)) {
      delete labels[eventKey];
      updateBrandConfig({ primary_events: list.filter(e => e !== eventKey), primary_event_labels: labels });
    } else {
      labels[eventKey] = label;
      updateBrandConfig({ primary_events: [...list, eventKey], primary_event_labels: labels });
    }
  };

  const toggleVisibleMetric = (key) => {
    const list = brandConfig.visible_metrics || [];
    const next = list.includes(key) ? list.filter(k => k !== key) : [...list, key];
    updateBrandConfig({ visible_metrics: next });
  };

  // v6.6: toggle for table-view metrics
  const toggleTableVisibleMetric = (key) => {
    const list = brandConfig.table_visible_metrics || [];
    const next = list.includes(key) ? list.filter(k => k !== key) : [...list, key];
    updateBrandConfig({ table_visible_metrics: next });
  };

  const toggleThresholdMetric = (key) => {
    const list = brandConfig.threshold_metrics || [];
    const newThresholds = { ...brandConfig.thresholds };
    if (list.includes(key)) {
      delete newThresholds[key];
      updateBrandConfig({ threshold_metrics: list.filter(k => k !== key), thresholds: newThresholds });
    } else {
      updateBrandConfig({ threshold_metrics: [...list, key] });
    }
  };

  const updateThreshold = (metric, type, value) => {
    const numValue = value === '' ? null : parseFloat(value);
    const newThresholds = {
      ...brandConfig.thresholds,
      [metric]: { ...(brandConfig.thresholds[metric] || {}), [type]: numValue },
    };
    updateBrandConfig({ thresholds: newThresholds });
  };

  // v6.6: copy card visible_metrics til table_visible_metrics
  const copyFromCardView = () => {
    updateBrandConfig({ table_visible_metrics: [...(brandConfig.visible_metrics || [])] });
  };

  const handleSelectPreset = async (id) => {
    try {
      await fetch(`/api/presets/${id}/activate`, { method: 'POST' });
      setActivePresetId(id);
      const preset = allPresets.find(p => p.id === id);
      if (preset) setConfig(JSON.parse(preset.config_json));
      const r = await fetch('/api/presets');
      const data = await r.json();
      setAllPresets(data.presets || []);
      if (onPresetChange) onPresetChange(preset);
    } catch (err) { setError(String(err)); }
  };

  const handleSave = async () => {
    if (!activePresetId) return;
    try {
      const r = await fetch(`/api/presets/${activePresetId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ config }),
      });
      if (!r.ok) throw new Error((await r.json()).error || 'Fejl');
      setSavedFlash(true);
      setTimeout(() => setSavedFlash(false), 1500);
      await loadPresets();
      if (onPresetChange) onPresetChange(allPresets.find(p => p.id === activePresetId));
    } catch (err) { setError(String(err)); }
  };

  const handleNewPreset = async () => {
    const name = prompt('Navn på det nye preset:');
    if (!name) return;
    try {
      const r = await fetch('/api/presets', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name, config }),
      });
      const data = await r.json();
      if (!r.ok) throw new Error(data.error || 'Fejl');
      await fetch(`/api/presets/${data.preset.id}/activate`, { method: 'POST' });
      await loadPresets();
      setActivePresetId(data.preset.id);
      if (onPresetChange) onPresetChange(data.preset);
    } catch (err) { setError(String(err)); }
  };

  const handleDelete = async () => {
    if (!activePresetId || isDefault) return;
    if (!confirm(`Slet preset "${activePreset?.name}"?`)) return;
    try {
      const r = await fetch(`/api/presets/${activePresetId}`, { method: 'DELETE' });
      const data = await r.json();
      if (!r.ok) throw new Error(data.error || 'Fejl');
      await loadPresets();
      if (data.active) setActivePresetId(data.active.id);
      if (onPresetChange) onPresetChange(data.active);
    } catch (err) { setError(String(err)); }
  };

  const handleResetDefault = async () => {
    if (!isDefault) return;
    if (!confirm('Reset Default-preset til fabrikssetting?')) return;
    try {
      await fetch('/api/presets/default/reset', { method: 'POST' });
      await loadPresets();
      if (onPresetChange) onPresetChange(activePreset);
    } catch (err) { setError(String(err)); }
  };

  const handleRename = async () => {
    if (!activePresetId || isDefault) return;
    const newName = prompt('Nyt navn:', activePreset?.name);
    if (!newName || newName === activePreset?.name) return;
    try {
      const r = await fetch(`/api/presets/${activePresetId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: newName }),
      });
      if (!r.ok) throw new Error((await r.json()).error || 'Fejl');
      await loadPresets();
    } catch (err) { setError(String(err)); }
  };

  if (!open) return null;

  const primaryEvents = brandConfig.primary_events || [];
  const visibleMetrics = brandConfig.visible_metrics || [];
  const tableVisibleMetrics = brandConfig.table_visible_metrics || [];
  const thresholdMetrics = brandConfig.threshold_metrics || [];

  const renderEventsSection = () => (
    <>
      <div className="settings-section__hint">
        Vælg én eller flere konverteringer der er primære for {BRANDS_LIST.find(b => b.id === selectedBrand)?.label}.
      </div>
      <div className="settings-section__sublabel">Standard events</div>
      <div className="settings-event-grid">
        {STANDARD_EVENTS.map(e => (
          <label key={e.value} className="settings-checkbox">
            <input type="checkbox" checked={primaryEvents.includes(e.value)} onChange={() => toggleEvent(e.value, e.label)} />
            {e.label}
          </label>
        ))}
      </div>
      {conversions.length > 0 && (
        <>
          <div className="settings-section__sublabel">Custom conversions</div>
          <div className="settings-event-grid">
            {conversions.map(c => {
              const eventKey = `offsite_conversion.custom.${c.cc_id}`;
              return (
                <label key={c.cc_id} className="settings-checkbox">
                  <input type="checkbox" checked={primaryEvents.includes(eventKey)} onChange={() => toggleEvent(eventKey, c.name)} />
                  <span className="settings-event-label">
                    {c.name}
                    <span className="settings-event-type">({c.custom_event_type})</span>
                  </span>
                </label>
              );
            })}
          </div>
        </>
      )}
    </>
  );

  const renderMetricsSection = (metricsList, toggleFn, sectionLabel) => {
    const grouped = {
      core: METRIC_DEFINITIONS.filter(m => m.category === 'core'),
      click: METRIC_DEFINITIONS.filter(m => m.category === 'click'),
      lpv: METRIC_DEFINITIONS.filter(m => m.category === 'lpv'),
      video: METRIC_DEFINITIONS.filter(m => m.category === 'video'),
    };

    return (
      <>
        {[
          { key: 'core', label: 'Core' },
          { key: 'click', label: 'Click metrics' },
          { key: 'lpv', label: 'Landing page' },
          { key: 'video', label: 'Video' },
        ].map(group => (
          <div key={group.key} className="settings-metric-group">
            <div className="settings-section__sublabel">{group.label}</div>
            <div className="settings-event-grid">
              {grouped[group.key].map(m => (
                <label key={m.key} className="settings-checkbox">
                  <input type="checkbox" checked={metricsList.includes(m.key)} onChange={() => toggleFn(m.key)} />
                  {m.label}
                </label>
              ))}
            </div>
          </div>
        ))}
      </>
    );
  };

  const renderCardMetricsSection = () => (
    <>
      <div className="settings-section__hint">
        Hvilke metrics vises på kortene i Cards-view for {BRANDS_LIST.find(b => b.id === selectedBrand)?.label}?
      </div>
      {renderMetricsSection(visibleMetrics, toggleVisibleMetric)}
    </>
  );

  // v6.6: ny sektion for tabel-metrics
  const renderTableMetricsSection = () => (
    <>
      <div className="settings-section__hint">
        Hvilke metrics vises som kolonner i Table-view for {BRANDS_LIST.find(b => b.id === selectedBrand)?.label}?
      </div>
      <div className="settings-table-actions">
        <button className="settings-btn" onClick={copyFromCardView}>
          Kopiér fra Cards-view ({visibleMetrics.length} metrics)
        </button>
      </div>
      {renderMetricsSection(tableVisibleMetrics, toggleTableVisibleMetric)}
    </>
  );

  const renderThresholdsSection = () => (
    <>
      <div className="settings-section__hint">
        Toggle metrics der skal have thresholds. For aktive metrics, sæt god/dårlig grænser.
      </div>
      <div className="settings-section__sublabel">Standard metrics</div>
      {METRIC_DEFINITIONS.filter(m => m.higherBetter !== null).map(m => {
        const isActive = thresholdMetrics.includes(m.key);
        const th = brandConfig.thresholds[m.key] || {};
        return (
          <div key={m.key} className={`settings-threshold-row ${isActive ? '' : 'settings-threshold-row--inactive'}`}>
            <label className="settings-threshold-toggle">
              <input type="checkbox" checked={isActive} onChange={() => toggleThresholdMetric(m.key)} />
              <span className="settings-threshold-label">{m.label}</span>
            </label>
            {isActive && (
              <div className="settings-threshold-inputs">
                <div className="settings-threshold-input-group">
                  <span className="settings-threshold-prefix">{m.higherBetter ? 'God: >' : 'God: <'}</span>
                  <input type="number" step="0.01" className="settings-input settings-input--small"
                    value={th.good ?? ''} onChange={(e) => updateThreshold(m.key, 'good', e.target.value)} />
                  {m.unit && <span className="settings-threshold-unit">{m.unit}</span>}
                </div>
                <div className="settings-threshold-input-group">
                  <span className="settings-threshold-prefix">{m.higherBetter ? 'Dårlig: <' : 'Dårlig: >'}</span>
                  <input type="number" step="0.01" className="settings-input settings-input--small"
                    value={th.bad ?? ''} onChange={(e) => updateThreshold(m.key, 'bad', e.target.value)} />
                  {m.unit && <span className="settings-threshold-unit">{m.unit}</span>}
                </div>
              </div>
            )}
          </div>
        );
      })}

      {primaryEvents.length > 0 && (
        <>
          <div className="settings-section__sublabel" style={{marginTop: '16px'}}>Konvertering thresholds</div>
          {primaryEvents.map(eventKey => {
            const label = brandConfig.primary_event_labels?.[eventKey] || eventKey;
            const isCustomPurchase = conversions.find(c =>
              `offsite_conversion.custom.${c.cc_id}` === eventKey && c.custom_event_type === 'PURCHASE'
            );
            const showRoas = eventKey === 'purchase' || isCustomPurchase;

            return (
              <div key={eventKey} className="settings-conv-block">
                <div className="settings-conv-label">★ {label}</div>
                {[
                  { suffix: 'count', label: 'Antal', higherBetter: true, unit: '' },
                  { suffix: 'cpa', label: 'CPA', higherBetter: false, unit: 'eur' },
                  ...(showRoas ? [{ suffix: 'roas', label: 'ROAS', higherBetter: true, unit: '' }] : []),
                ].map(metric => {
                  const thKey = `conv:${eventKey}:${metric.suffix}`;
                  const isActive = thresholdMetrics.includes(thKey);
                  const th = brandConfig.thresholds[thKey] || {};
                  return (
                    <div key={thKey} className={`settings-threshold-row settings-threshold-row--conv ${isActive ? '' : 'settings-threshold-row--inactive'}`}>
                      <label className="settings-threshold-toggle">
                        <input type="checkbox" checked={isActive} onChange={() => toggleThresholdMetric(thKey)} />
                        <span className="settings-threshold-label">{metric.label}</span>
                      </label>
                      {isActive && (
                        <div className="settings-threshold-inputs">
                          <div className="settings-threshold-input-group">
                            <span className="settings-threshold-prefix">{metric.higherBetter ? 'God: >' : 'God: <'}</span>
                            <input type="number" step="0.01" className="settings-input settings-input--small"
                              value={th.good ?? ''} onChange={(e) => updateThreshold(thKey, 'good', e.target.value)} />
                            {metric.unit && <span className="settings-threshold-unit">{metric.unit}</span>}
                          </div>
                          <div className="settings-threshold-input-group">
                            <span className="settings-threshold-prefix">{metric.higherBetter ? 'Dårlig: <' : 'Dårlig: >'}</span>
                            <input type="number" step="0.01" className="settings-input settings-input--small"
                              value={th.bad ?? ''} onChange={(e) => updateThreshold(thKey, 'bad', e.target.value)} />
                            {metric.unit && <span className="settings-threshold-unit">{metric.unit}</span>}
                          </div>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            );
          })}
        </>
      )}
    </>
  );

  return (
    <>
      <div className="settings-backdrop" onClick={onClose} />
      <div className="settings-panel">
        <div className="settings-panel__header">
          <div className="settings-panel__title">
            <svg viewBox="0 0 24 24" width="20" height="20"><circle cx="12" cy="12" r="3" fill="none" stroke="currentColor" strokeWidth="2"/><path d="M12 1v4M12 19v4M4.22 4.22l2.83 2.83M16.95 16.95l2.83 2.83M1 12h4M19 12h4M4.22 19.78l2.83-2.83M16.95 7.05l2.83-2.83" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>
            Settings
          </div>
          <button className="settings-panel__close" onClick={onClose} aria-label="Luk">
            <svg viewBox="0 0 24 24" width="20" height="20"><path d="M6 6 L18 18 M18 6 L6 18" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"/></svg>
          </button>
        </div>

        <div className="settings-panel__body">
          {loading ? (
            <div className="settings-panel__loading">Henter settings...</div>
          ) : error ? (
            <div className="settings-panel__error">Fejl: {error}</div>
          ) : (
            <>
              <div className="settings-section">
                <div className="settings-section__label">Preset</div>
                <select className="settings-input" value={activePresetId || ''} onChange={(e) => handleSelectPreset(parseInt(e.target.value))}>
                  {allPresets.map(p => (
                    <option key={p.id} value={p.id}>{p.name}{p.is_default ? ' (Default)' : ''}</option>
                  ))}
                </select>
                <div className="settings-preset-actions">
                  <button className="settings-btn settings-btn--primary" onClick={handleSave}>{savedFlash ? '✓ Gemt' : 'Gem'}</button>
                  <button className="settings-btn" onClick={handleNewPreset}>Nyt</button>
                  {!isDefault && (<>
                    <button className="settings-btn" onClick={handleRename}>Omdøb</button>
                    <button className="settings-btn settings-btn--danger" onClick={handleDelete}>Slet</button>
                  </>)}
                  {isDefault && <button className="settings-btn settings-btn--reset" onClick={handleResetDefault}>Reset til fabrikssetting</button>}
                </div>
                {isDefault && <div className="settings-info">ⓘ Default-preset kan ikke slettes</div>}
              </div>

              <div className="settings-section">
                <div className="settings-section__label">Brand</div>
                <div className="settings-brand-tabs">
                  {BRANDS_LIST.map(b => (
                    <button key={b.id}
                      className={`settings-brand-tab ${selectedBrand === b.id ? 'settings-brand-tab--active' : ''}`}
                      onClick={() => setSelectedBrand(b.id)}>{b.label}</button>
                  ))}
                </div>
              </div>

              {/* v6.6: 4 sektion-tabs */}
              <div className="settings-section-tabs">
                {[
                  { id: 'events', label: `Konverteringer (${primaryEvents.length})` },
                  { id: 'metrics', label: `Cards (${visibleMetrics.length})` },
                  { id: 'tableMetrics', label: `Table (${tableVisibleMetrics.length})` },
                  { id: 'thresholds', label: `Thresholds (${thresholdMetrics.length})` },
                ].map(t => (
                  <button key={t.id}
                    className={`settings-section-tab ${activeSection === t.id ? 'settings-section-tab--active' : ''}`}
                    onClick={() => setActiveSection(t.id)}>{t.label}</button>
                ))}
              </div>

              <div className="settings-section">
                {activeSection === 'events' && renderEventsSection()}
                {activeSection === 'metrics' && renderCardMetricsSection()}
                {activeSection === 'tableMetrics' && renderTableMetricsSection()}
                {activeSection === 'thresholds' && renderThresholdsSection()}
              </div>
            </>
          )}
        </div>
      </div>
    </>
  );
};
