// CategoryEditor.jsx v1
// Editor til at bygge kategorier med rules og grupper (Niveau B: AND/OR)

const PRESET_COLORS = [
  { id: 'green',  hex: '#2e7d32', label: 'Grøn' },
  { id: 'red',    hex: '#c62828', label: 'Rød' },
  { id: 'yellow', hex: '#f9a825', label: 'Gul' },
  { id: 'blue',   hex: '#1877f2', label: 'Blå' },
  { id: 'purple', hex: '#7b1fa2', label: 'Lilla' },
  { id: 'gray',   hex: '#65676b', label: 'Grå' },
];

const OPERATORS = [
  { value: '>',  label: '>' },
  { value: '<',  label: '<' },
  { value: '>=', label: '≥' },
  { value: '<=', label: '≤' },
  { value: '=',  label: '=' },
  { value: '!=', label: '≠' },
];

// Generér unikt id
function genId() {
  return 'cat_' + Math.random().toString(36).substring(2, 10);
}

// Lav nem id-tilgang ved ny rule
function genRuleId() {
  return 'rule_' + Math.random().toString(36).substring(2, 10);
}

const CategoryEditor = ({ categories, brand, brandConfig, conversions, ads, onChange }) => {
  const fmt = window.AppMetrics;
  const METRIC_DEFINITIONS = fmt?.METRIC_DEFINITIONS || [];

  // Bygger metric-options til dropdown
  // Standard metrics + conversion metrics for valgte primary events
  const metricOptions = React.useMemo(() => {
    const standard = METRIC_DEFINITIONS.map(m => ({ value: m.key, label: m.label }));
    const conv = [];
    const primaryEvents = brandConfig?.primary_events || [];
    for (const eventKey of primaryEvents) {
      const label = brandConfig?.primary_event_labels?.[eventKey] || eventKey;
      conv.push(
        { value: `conv:${eventKey}:count`, label: `${label} - Antal` },
        { value: `conv:${eventKey}:cpa`,   label: `${label} - CPA` },
      );
      // ROAS kun for purchase-typer
      const isCustomPurchase = conversions.find(c =>
        `offsite_conversion.custom.${c.cc_id}` === eventKey && c.custom_event_type === 'PURCHASE'
      );
      const showRoas = eventKey === 'purchase' || isCustomPurchase;
      if (showRoas) {
        conv.push({ value: `conv:${eventKey}:roas`, label: `${label} - ROAS` });
      }
    }
    return { standard, conv };
  }, [brandConfig, conversions]);

  // Tæl matchende ads for live preview
  const countMatching = (cat) => fmt?.countAdsMatchingCategory(cat, ads, brand) ?? 0;

  // ===== Mutators =====

  const updateCategory = (catId, updates) => {
    onChange(categories.map(c => c.id === catId ? { ...c, ...updates } : c));
  };

  const removeCategory = (catId) => {
    if (!confirm('Slet kategorien?')) return;
    onChange(categories.filter(c => c.id !== catId));
  };

  const moveCategoryUp = (catId) => {
    const idx = categories.findIndex(c => c.id === catId);
    if (idx <= 0) return;
    const next = [...categories];
    [next[idx - 1], next[idx]] = [next[idx], next[idx - 1]];
    onChange(next);
  };

  const moveCategoryDown = (catId) => {
    const idx = categories.findIndex(c => c.id === catId);
    if (idx === -1 || idx >= categories.length - 1) return;
    const next = [...categories];
    [next[idx], next[idx + 1]] = [next[idx + 1], next[idx]];
    onChange(next);
  };

  const addCategory = () => {
    const newCat = {
      id: genId(),
      label: 'Ny kategori',
      color: '#1877f2',
      groups: [{ rules: [{ id: genRuleId(), metric: 'spend', op: '>', value: 0 }] }],
    };
    onChange([...categories, newCat]);
  };

  const updateGroup = (catId, groupIdx, updates) => {
    const cat = categories.find(c => c.id === catId);
    if (!cat) return;
    const newGroups = cat.groups.map((g, i) => i === groupIdx ? { ...g, ...updates } : g);
    updateCategory(catId, { groups: newGroups });
  };

  const addGroup = (catId) => {
    const cat = categories.find(c => c.id === catId);
    if (!cat) return;
    const newGroups = [...cat.groups, { rules: [{ id: genRuleId(), metric: 'spend', op: '>', value: 0 }] }];
    updateCategory(catId, { groups: newGroups });
  };

  const removeGroup = (catId, groupIdx) => {
    const cat = categories.find(c => c.id === catId);
    if (!cat) return;
    if (cat.groups.length <= 1) {
      alert('Kategorien skal have mindst én gruppe');
      return;
    }
    updateCategory(catId, { groups: cat.groups.filter((_, i) => i !== groupIdx) });
  };

  const updateRule = (catId, groupIdx, ruleIdx, updates) => {
    const cat = categories.find(c => c.id === catId);
    if (!cat) return;
    const newGroups = cat.groups.map((g, gi) => {
      if (gi !== groupIdx) return g;
      return {
        ...g,
        rules: g.rules.map((r, ri) => ri === ruleIdx ? { ...r, ...updates } : r),
      };
    });
    updateCategory(catId, { groups: newGroups });
  };

  const addRule = (catId, groupIdx) => {
    const cat = categories.find(c => c.id === catId);
    if (!cat) return;
    const newGroups = cat.groups.map((g, gi) => {
      if (gi !== groupIdx) return g;
      return { ...g, rules: [...g.rules, { id: genRuleId(), metric: 'spend', op: '>', value: 0 }] };
    });
    updateCategory(catId, { groups: newGroups });
  };

  const removeRule = (catId, groupIdx, ruleIdx) => {
    const cat = categories.find(c => c.id === catId);
    if (!cat) return;
    const group = cat.groups[groupIdx];
    if (!group || group.rules.length <= 1) {
      alert('Gruppen skal have mindst én regel');
      return;
    }
    const newGroups = cat.groups.map((g, gi) => {
      if (gi !== groupIdx) return g;
      return { ...g, rules: g.rules.filter((_, ri) => ri !== ruleIdx) };
    });
    updateCategory(catId, { groups: newGroups });
  };

  // ===== Render =====

  return (
    <>
      <div className="settings-section__hint">
        Definér kategorier (fx Winner, Loser) baseret på conditions.
        Inden for en gruppe skal alle regler matche (AND). Mellem grupper er det OR.
        Første kategori der matcher vises på ad'et.
      </div>

      {categories.length === 0 && (
        <div className="cat-editor__empty">
          Ingen kategorier endnu. Klik "Tilføj kategori" for at starte.
        </div>
      )}

      {categories.map((cat, catIdx) => (
        <div key={cat.id} className="cat-editor__category" style={{borderLeftColor: cat.color}}>
          <div className="cat-editor__header">
            <input
              type="text"
              className="cat-editor__name-input"
              value={cat.label}
              onChange={(e) => updateCategory(cat.id, { label: e.target.value })}
              placeholder="Navn..."
            />
            <div className="cat-editor__color-picker">
              {PRESET_COLORS.map(c => (
                <button
                  key={c.id}
                  type="button"
                  className={`cat-editor__color-swatch ${cat.color === c.hex ? 'cat-editor__color-swatch--active' : ''}`}
                  style={{background: c.hex}}
                  onClick={() => updateCategory(cat.id, { color: c.hex })}
                  title={c.label}
                  aria-label={`Vælg ${c.label}`}
                />
              ))}
            </div>
            <div className="cat-editor__actions">
              <button className="cat-editor__action-btn" onClick={() => moveCategoryUp(cat.id)}
                disabled={catIdx === 0} title="Flyt op">↑</button>
              <button className="cat-editor__action-btn" onClick={() => moveCategoryDown(cat.id)}
                disabled={catIdx === categories.length - 1} title="Flyt ned">↓</button>
              <button className="cat-editor__action-btn cat-editor__action-btn--danger"
                onClick={() => removeCategory(cat.id)} title="Slet kategori">×</button>
            </div>
          </div>

          <div className="cat-editor__match-count">
            {countMatching(cat)} af {ads.length} annoncer matcher
          </div>

          {cat.groups.map((group, groupIdx) => (
            <React.Fragment key={`group-${groupIdx}`}>
              {groupIdx > 0 && (
                <div className="cat-editor__or-divider">
                  <span>ELLER</span>
                </div>
              )}
              <div className="cat-editor__group">
                <div className="cat-editor__group-header">
                  <span className="cat-editor__group-label">
                    Gruppe {groupIdx + 1} (alle skal være sande)
                  </span>
                  {cat.groups.length > 1 && (
                    <button className="cat-editor__action-btn cat-editor__action-btn--small"
                      onClick={() => removeGroup(cat.id, groupIdx)} title="Slet gruppe">×</button>
                  )}
                </div>

                {group.rules.map((rule, ruleIdx) => (
                  <div key={rule.id || ruleIdx} className="cat-editor__rule">
                    <select
                      className="cat-editor__metric-select"
                      value={rule.metric || ''}
                      onChange={(e) => updateRule(cat.id, groupIdx, ruleIdx, { metric: e.target.value })}
                    >
                      <optgroup label="Standard metrics">
                        {metricOptions.standard.map(m => (
                          <option key={m.value} value={m.value}>{m.label}</option>
                        ))}
                      </optgroup>
                      {metricOptions.conv.length > 0 && (
                        <optgroup label="Konverteringer">
                          {metricOptions.conv.map(m => (
                            <option key={m.value} value={m.value}>{m.label}</option>
                          ))}
                        </optgroup>
                      )}
                    </select>

                    <select
                      className="cat-editor__op-select"
                      value={rule.op || '>'}
                      onChange={(e) => updateRule(cat.id, groupIdx, ruleIdx, { op: e.target.value })}
                    >
                      {OPERATORS.map(o => (
                        <option key={o.value} value={o.value}>{o.label}</option>
                      ))}
                    </select>

                    <input
                      type="number"
                      step="0.01"
                      className="cat-editor__value-input"
                      value={rule.value ?? ''}
                      onChange={(e) => updateRule(cat.id, groupIdx, ruleIdx, { value: e.target.value })}
                      placeholder="Værdi"
                    />

                    <button
                      className="cat-editor__action-btn cat-editor__action-btn--small"
                      onClick={() => removeRule(cat.id, groupIdx, ruleIdx)}
                      title="Fjern regel"
                      disabled={group.rules.length <= 1}
                    >×</button>
                  </div>
                ))}

                <button className="cat-editor__add-rule" onClick={() => addRule(cat.id, groupIdx)}>
                  + Tilføj regel
                </button>
              </div>
            </React.Fragment>
          ))}

          <button className="cat-editor__add-group" onClick={() => addGroup(cat.id)}>
            + Tilføj gruppe (ELLER)
          </button>
        </div>
      ))}

      <button className="cat-editor__add-category" onClick={addCategory}>
        + Tilføj kategori
      </button>
    </>
  );
};
