// Step 4 — Routing: per-GEO URL overrides, force URL, block list

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

  const setRoute = (g, v) => setDraft({ ...draft, geoRoutes: { ...draft.geoRoutes, [g]: v } });

  const resetToDefault = (g) => setRoute(g, draft.defaultUrl);

  const isDefault = (g) => !draft.geoRoutes[g] || draft.geoRoutes[g] === draft.defaultUrl;

  return (
    <div className="step-anim">
      <SectionTitle
        kicker="Step 04 / 07"
        title="Route by country"
        desc="By default every GEO sends users to the brand's default URL. Override here when one country needs a different offer or sub-affiliate ID."
      />

      {draft.geos.length === 0 ? (
        <div className="panel" style={{ padding: '60px 24px', textAlign: 'center' }}>
          <div style={{ fontSize: 48, marginBottom: 12, opacity: 0.4 }}>🌍</div>
          <h3 style={{ fontSize: 16, fontWeight: 600, marginBottom: 6 }}>No countries selected</h3>
          <p style={{ color: 'var(--muted)', fontSize: 13 }}>Go back to step 3 to pick at least one target country.</p>
        </div>
      ) : (
        <>
          <div className="panel" style={{ padding: 0, overflow: 'hidden' }}>
            <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--line-soft)', display: 'flex', alignItems: 'center', gap: 12 }}>
              <div>
                <div style={{ fontSize: 14, fontWeight: 600 }}>Per-country URLs</div>
                <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>Override the default for specific GEOs. Leave on “Use default” to keep things simple.</div>
              </div>
              <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
                <button
                  className="btn ghost small"
                  onClick={() => {
                    const newRoutes = {};
                    draft.geos.forEach(g => newRoutes[g] = draft.defaultUrl);
                    setDraft({ ...draft, geoRoutes: newRoutes });
                  }}
                >Reset all to default</button>
              </div>
            </div>

            <div style={{ padding: '4px 0' }}>
              {draft.geos.map((g, i) => {
                const def = isDefault(g);
                return (
                  <div key={g} style={{
                    display: 'grid', gridTemplateColumns: '40px 1fr 1fr auto auto', gap: 12,
                    alignItems: 'center',
                    padding: '12px 20px',
                    borderTop: i > 0 ? '1px solid var(--line-soft)' : 'none',
                  }}>
                    <div style={{ fontSize: 22 }}>{COUNTRY_FLAGS[g]}</div>
                    <div>
                      <div style={{ fontSize: 13, fontWeight: 500 }}>{COUNTRY_NAMES[g]}</div>
                      <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: 'var(--muted)' }}>{g}</div>
                    </div>
                    <input
                      type="text"
                      className="mono"
                      value={draft.geoRoutes[g] || ''}
                      onChange={e => setRoute(g, e.target.value)}
                      placeholder={draft.defaultUrl || 'https://...'}
                      style={{
                        padding: '8px 10px',
                        background: 'var(--bg-0)',
                        border: `1px solid ${def ? 'var(--line)' : 'var(--accent-line)'}`,
                        borderRadius: 6,
                        color: def ? 'var(--muted)' : 'var(--text)',
                        fontSize: 11.5,
                      }}
                    />
                    <span className={`pill ${def ? '' : 'live'}`} style={{ minWidth: 90, justifyContent: 'center' }}>
                      {def ? 'DEFAULT' : (
                        <>
                          <window.IconCheck size={9} sw={3} />OVERRIDE
                        </>
                      )}
                    </span>
                    <button
                      className="btn ghost small"
                      onClick={() => resetToDefault(g)}
                      disabled={def}
                      style={{ opacity: def ? 0.3 : 1 }}
                    >Reset</button>
                  </div>
                );
              })}
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 18 }}>
            <div className="panel" style={{ padding: 22 }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: 14 }}>
                <div style={{ width: 36, height: 36, borderRadius: 9, background: 'var(--warn-dim)', color: 'var(--warn)', border: '1px solid rgba(255,195,107,0.3)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                  <window.IconAlert size={18} />
                </div>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>Force URL override</div>
                  <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>If set, ignores all GEO routing and always returns this URL. Useful for A/B testing or emergency rotations.</div>
                </div>
              </div>
              <input
                type="text"
                className="mono"
                value={draft.forceUrl}
                onChange={e => setDraft({ ...draft, forceUrl: e.target.value })}
                placeholder="(empty — use GEO routing)"
                style={{
                  width: '100%', padding: '10px 12px',
                  background: 'var(--bg-0)', border: '1px solid var(--line)', borderRadius: 7,
                  color: 'var(--text)', fontSize: 12,
                }}
              />
            </div>

            <div className="panel" style={{ padding: 22 }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: 14 }}>
                <div style={{ width: 36, height: 36, borderRadius: 9, background: 'var(--danger-dim)', color: 'var(--danger)', border: '1px solid rgba(255,90,110,0.3)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                  <window.IconShield size={18} />
                </div>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>Block countries</div>
                  <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>Returns empty for users from these 2-letter codes, who'll then see your fallback page instead.</div>
                </div>
              </div>
              <input
                type="text"
                value={(draft.blockCountries || []).join(', ')}
                onChange={e => setDraft({ ...draft, blockCountries: e.target.value.split(',').map(s => s.trim().toUpperCase()).filter(s => /^[A-Z]{2}$/.test(s)) })}
                placeholder="US, IL, UK"
                className="mono"
                style={{
                  width: '100%', padding: '10px 12px',
                  background: 'var(--bg-0)', border: '1px solid var(--line)', borderRadius: 7,
                  color: 'var(--text)', fontSize: 12,
                }}
              />
              {draft.blockCountries?.length > 0 && (
                <div style={{ marginTop: 8, display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                  {draft.blockCountries.map(c => (
                    <span key={c} className="pill paused" style={{ fontSize: 10 }}>
                      {COUNTRY_FLAGS[c] || '🌐'} {c}
                    </span>
                  ))}
                </div>
              )}
            </div>
          </div>
        </>
      )}
    </div>
  );
};

window.Step4Routing = Step4Routing;
