// Step 3 — Brand & GEOs: choose Royal Partners brand, pick target countries

const Step3Brand = ({ draft, setDraft }) => {
  const { BRANDS, COUNTRY_FLAGS, COUNTRY_NAMES, SectionTitle, ChoiceCard, IconCheck } = window;

  const pickBrand = (b) => {
    const brand = BRANDS[b];
    const next = { ...draft, brand: b };
    if (b !== 'CUSTOM' && brand) {
      next.geos = [...brand.geos];
      const newRoutes = { ...draft.geoRoutes };
      brand.geos.forEach(g => { if (!newRoutes[g]) newRoutes[g] = draft.defaultUrl || ''; });
      next.geoRoutes = newRoutes;
    }
    setDraft(next);
  };

  const toggleGeo = (g) => {
    if (draft.geos.includes(g)) {
      const newRoutes = { ...draft.geoRoutes };
      delete newRoutes[g];
      setDraft({ ...draft, geos: draft.geos.filter(x => x !== g), geoRoutes: newRoutes });
    } else {
      setDraft({
        ...draft,
        geos: [...draft.geos, g],
        geoRoutes: { ...draft.geoRoutes, [g]: draft.defaultUrl || '' },
      });
    }
  };

  const allGeos = Object.keys(COUNTRY_FLAGS);

  return (
    <div className="step-anim">
      <SectionTitle
        kicker="Step 03 / 07"
        title="Pick a brand & where it converts"
        desc="The brand decides the affiliate URL pool. The countries decide who gets routed to it — anyone outside this list will fall back or be blocked."
      />

      <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600, marginBottom: 12, paddingLeft: 2 }}>
        Royal Partners brand
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 28 }}>
        {Object.entries(BRANDS).map(([k, b]) => {
          const active = draft.brand === k;
          return (
            <ChoiceCard key={k} active={active} onClick={() => pickBrand(k)} accent={b.color}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
                <div style={{
                  width: 36, height: 36, borderRadius: 9,
                  background: `${b.color}1A`, border: `1px solid ${b.color}40`,
                  display: 'grid', placeItems: 'center',
                  color: b.color, fontWeight: 700, fontSize: 14,
                  fontFamily: 'JetBrains Mono, monospace',
                }}>{k.slice(0, 2)}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>{b.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--muted)' }}>{b.tagline}</div>
                </div>
                {active && (
                  <div style={{ width: 16, height: 16, borderRadius: '50%', background: b.color, color: '#001a0c', display: 'grid', placeItems: 'center' }}>
                    <IconCheck size={10} sw={3} />
                  </div>
                )}
              </div>
              {b.geos.length > 0 ? (
                <div style={{ display: 'flex', gap: 3, flexWrap: 'wrap' }}>
                  {b.geos.map(g => (
                    <span key={g} style={{ fontSize: 13 }} title={COUNTRY_NAMES[g]}>{COUNTRY_FLAGS[g]}</span>
                  ))}
                </div>
              ) : (
                <div style={{ fontSize: 11, color: 'var(--muted-2)', fontStyle: 'italic' }}>You choose</div>
              )}
            </ChoiceCard>
          );
        })}
      </div>

      <div className="panel" style={{ padding: 24 }}>
        <div className="field">
          <label>Default affiliate URL</label>
          <input
            type="text"
            className="mono"
            value={draft.defaultUrl}
            onChange={e => {
              const v = e.target.value;
              // Auto-populate empty per-geo entries with new default
              const newRoutes = { ...draft.geoRoutes };
              draft.geos.forEach(g => { if (!newRoutes[g] || newRoutes[g] === draft.defaultUrl) newRoutes[g] = v; });
              setDraft({ ...draft, defaultUrl: v, geoRoutes: newRoutes });
            }}
            placeholder="https://irisroute61.com/c463dd534"
          />
          <div className="help">Used for any selected country that doesn't have its own override in step 4.</div>
        </div>

        <div className="field" style={{ marginBottom: 0 }}>
          <label>Target countries <span style={{ color: 'var(--accent)', fontFamily: 'JetBrains Mono, monospace', fontWeight: 600, textTransform: 'none', letterSpacing: 0 }}>{draft.geos.length} selected</span></label>

          {draft.brand && draft.brand !== 'CUSTOM' && (
            <div style={{
              fontSize: 11.5, color: 'var(--muted)', marginBottom: 12,
              padding: '8px 12px', background: 'var(--bg-2)', borderRadius: 7,
              display: 'flex', alignItems: 'center', gap: 8,
            }}>
              <window.IconAlert size={13} style={{ color: BRANDS[draft.brand]?.color }} />
              Recommended for {BRANDS[draft.brand]?.name}: {BRANDS[draft.brand].geos.join(', ')}. You can still add or remove.
            </div>
          )}

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(118px, 1fr))', gap: 6 }}>
            {allGeos.map(g => {
              const sel = draft.geos.includes(g);
              const recommended = draft.brand && draft.brand !== 'CUSTOM' && BRANDS[draft.brand].geos.includes(g);
              return (
                <button
                  key={g}
                  className="btn ghost"
                  onClick={() => toggleGeo(g)}
                  style={{
                    padding: '8px 10px',
                    justifyContent: 'flex-start',
                    gap: 8,
                    fontSize: 12.5,
                    border: `1px solid ${sel ? 'var(--accent)' : 'var(--line)'}`,
                    background: sel ? 'var(--accent-dim)' : 'var(--bg-0)',
                    color: sel ? 'var(--text)' : 'var(--text-dim)',
                    borderRadius: 7,
                    position: 'relative',
                  }}>
                  <span style={{ fontSize: 15 }}>{COUNTRY_FLAGS[g]}</span>
                  <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11.5 }}>{g}</span>
                  {recommended && !sel && (
                    <span style={{ position: 'absolute', top: 2, right: 4, width: 4, height: 4, borderRadius: '50%', background: 'var(--accent)' }}></span>
                  )}
                </button>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
};

window.Step3Brand = Step3Brand;
