const { useState, useMemo, Reveal, Icon, MagneticBtn, useLandingStats } = window;

const TABS = [
  { id: 'revendeur', label: 'REVENDEUR' },
  { id: 'evolution', label: "COMMISSION D'ÉVOLUTION" },
];

function Calculator() {
  const { packs } = useLandingStats();
  const [tab, setTab] = useState('revendeur');

  const calcPacks = [
    { id: 'starter', name: 'Starter', price: packs.starter.price, evoRate: packs.starter.commission / 100 },
    { id: 'pro',     name: 'Pro',     price: packs.pro.price,     evoRate: packs.pro.commission / 100 },
    { id: 'premium', name: 'Premium', price: packs.premium.price, evoRate: packs.premium.commission / 100 },
  ];

  return (
    <section className="section">
      <div className="container">
        <Reveal className="section-header" style={{ textAlign: 'center', alignItems: 'center', marginLeft: 'auto', marginRight: 'auto' }}>
          <h2 className="h2" style={{ textTransform: 'none' }}>
            <span style={{ fontSize: '1.15em' }}>Simule tes</span><br />
            <span className="serif-i" style={{ color: 'var(--accent)', fontWeight: 400 }}>revenus potentiels.</span>
          </h2>
          <p style={{ color: 'var(--ink-dim)', fontSize: 18, maxWidth: 520 }}>
            Deux sources de revenus. Teste des scénarios selon ton activité.
          </p>
        </Reveal>

        {/* ── Tabs style Demo (pleine largeur, underline accent) ── */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: `repeat(${TABS.length}, 1fr)`,
          borderBottom: '1px solid var(--line)',
          marginBottom: 40,
          position: 'relative',
        }}>
          {TABS.map(t => {
            const isActive = tab === t.id;
            return (
              <button key={t.id} onClick={() => setTab(t.id)} data-cursor="hover"
                style={{
                  position: 'relative', padding: '18px 8px',
                  background: 'transparent', border: 'none',
                  color: isActive ? 'var(--ink)' : 'var(--ink-mute)',
                  fontFamily: 'Geist, sans-serif',
                  fontSize: 12, fontWeight: isActive ? 600 : 500,
                  letterSpacing: '0.08em', textTransform: 'uppercase',
                  cursor: 'pointer', transition: 'color 0.25s ease',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                }}>
                {isActive && (
                  <span style={{
                    width: 6, height: 6, borderRadius: '50%',
                    background: 'var(--accent)',
                    boxShadow: '0 0 10px var(--accent-glow)',
                  }} />
                )}
                {t.label}
                {isActive && (
                  <span style={{
                    position: 'absolute', bottom: -1, left: '8%', right: '8%', height: 1.5,
                    background: 'var(--accent)',
                    boxShadow: '0 0 8px var(--accent-glow)',
                  }} />
                )}
              </button>
            );
          })}
        </div>

        {tab === 'revendeur' ? <RevendeurTab calcPacks={calcPacks} /> : <EvolutionTab calcPacks={calcPacks} />}
      </div>
    </section>
  );
}

/* ═══ ONGLET 1 : REVENDEUR — 100% des droits de revente ═══ */
function RevendeurTab({ calcPacks }) {
  const [packIdx, setPackIdx] = useState(1);
  const [sales, setSales] = useState(8);

  const pack = calcPacks[packIdx];
  const revenuePerSale = pack.price; // 100% pour toi
  const monthly = revenuePerSale * sales;
  const yearly = monthly * 12;

  return (
    <Reveal>
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1.1fr', gap: 28,
        background: 'var(--bg-card)', border: '1px solid var(--line)',
        borderRadius: 24, padding: 28,
      }}>
        {/* ── Panneau gauche ── */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>

          {/* Pack selector — cards visuelles */}
          <div style={{ marginBottom: 20 }}>
            <span className="label" style={{ marginBottom: 10, display: 'block' }}>Pack que tu revends</span>
            <div style={{ display: 'flex', gap: 8 }}>
              {calcPacks.map((p, i) => {
                const sel = packIdx === i;
                return (
                  <button key={p.id} onClick={() => setPackIdx(i)} data-cursor="hover"
                    style={{
                      flex: 1, padding: '12px 10px', borderRadius: 12,
                      background: sel
                        ? 'color-mix(in oklab, var(--accent) 8%, var(--bg-card))'
                        : 'var(--bg-elev)',
                      border: sel ? '1px solid var(--accent)' : '1px solid var(--line)',
                      boxShadow: sel ? '0 0 24px -6px var(--accent-glow)' : 'none',
                      cursor: 'pointer',
                      transition: 'all 0.3s cubic-bezier(.2,.7,.2,1)',
                      textAlign: 'center',
                      transform: sel ? 'translateY(-2px)' : 'translateY(0)',
                    }}
                  >
                    <div style={{
                      fontSize: 20, lineHeight: 1,
                      fontFamily: 'Geist, sans-serif', fontWeight: 800,
                      color: sel ? 'var(--accent)' : 'var(--ink)',
                      transition: 'color 0.25s',
                    }}>{p.price}€</div>
                    <div style={{
                      fontSize: 11, fontWeight: 600, marginTop: 4,
                      color: sel ? 'var(--ink)' : 'var(--ink-dim)',
                    }}>{p.name}</div>
                    <div className="mono" style={{
                      fontSize: 8, marginTop: 4,
                      color: 'var(--accent)', letterSpacing: '0.05em',
                      opacity: sel ? 1 : 0.5,
                    }}>100% POUR TOI</div>
                  </button>
                );
              })}
            </div>
          </div>

          <CalcSlider
            label="Ventes par mois"
            value={sales} min={1} max={50} step={1}
            onChange={setSales}
            format={v => `${v} ventes`}
          />

          {/* Détail par vente — compact */}
          <div style={{
            marginTop: 4, padding: '14px 16px', borderRadius: 14,
            background: 'var(--bg-elev)', border: '1px solid var(--line)',
          }}>
            <span className="label" style={{ marginBottom: 10, display: 'block' }}>Détail par vente</span>
            <DetailRow left="Prix du pack" right={`${pack.price} €`} />
            <DetailRow left="Droits de revente" right="100 %" accent />
            <div style={{
              marginTop: 10, paddingTop: 10,
              borderTop: '1px solid var(--line)',
              display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
            }}>
              <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>Tu encaisses</span>
              <span style={{ fontSize: 20, fontFamily: 'Geist, sans-serif', fontWeight: 800, color: 'var(--accent)', letterSpacing: '-0.02em' }}>{revenuePerSale} €</span>
            </div>
          </div>
        </div>

        {/* ── Résultat ── */}
        <ResultPanel monthly={monthly} yearly={yearly} label="Revenus revendeur" sub="100% des ventes — tu gardes tout." />
      </div>
    </Reveal>
  );
}

/* ═══ ONGLET 2 : COMMISSION D'ÉVOLUTION — 25/50/75% ═══ */
function EvolutionTab({ calcPacks }) {
  const [fromIdx, setFromIdx] = useState(0);
  const [toIdx, setToIdx] = useState(2);
  const [upgrades, setUpgrades] = useState(5);

  const fromPack = calcPacks[fromIdx];
  const toPack = calcPacks[toIdx];
  const diff = toPack.price - fromPack.price;
  const commRate = toPack.evoRate;
  const commPerUpgrade = diff > 0 ? diff * commRate : 0;
  const monthly = commPerUpgrade * upgrades;
  const yearly = monthly * 12;

  return (
    <Reveal>
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1.1fr', gap: 28,
        background: 'var(--bg-card)', border: '1px solid var(--line)',
        borderRadius: 24, padding: 28,
      }}>
        {/* ── Panneau gauche ── */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>

          {/* Sélecteurs de → vers, sur une seule ligne */}
          <div style={{ marginBottom: 20 }}>
            <span className="label" style={{ marginBottom: 10, display: 'block' }}>Membre : de quel pack vers lequel ?</span>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              {/* Pack de départ */}
              <div style={{ display: 'flex', flex: 1, gap: 6 }}>
                {calcPacks.slice(0, 2).map((p, i) => {
                  const sel = fromIdx === i;
                  return (
                    <button key={p.id} data-cursor="hover"
                      onClick={() => { setFromIdx(i); if (toIdx <= i) setToIdx(i + 1); }}
                      style={{
                        flex: 1, padding: '10px 8px', borderRadius: 10,
                        background: sel ? 'var(--bg-elev)' : 'transparent',
                        border: sel ? '1px solid var(--line-strong)' : '1px solid var(--line)',
                        cursor: 'pointer', transition: 'all 0.25s', textAlign: 'center',
                      }}
                    >
                      <div style={{ fontSize: 15, fontFamily: 'Geist, sans-serif', fontWeight: 700, color: sel ? 'var(--ink)' : 'var(--ink-mute)', lineHeight: 1 }}>{p.price}€</div>
                      <div style={{ fontSize: 10, fontWeight: 600, marginTop: 3, color: sel ? 'var(--ink-dim)' : 'var(--ink-mute)' }}>{p.name}</div>
                    </button>
                  );
                })}
              </div>
              {/* Flèche */}
              <div style={{ color: 'var(--accent)', flexShrink: 0, display: 'flex', alignItems: 'center' }}>
                <Icon.Arrow size={16} />
              </div>
              {/* Pack cible */}
              <div style={{ display: 'flex', flex: 1, gap: 6 }}>
                {calcPacks.filter((_, i) => i > fromIdx).map(p => {
                  const idx = calcPacks.indexOf(p);
                  const sel = toIdx === idx;
                  return (
                    <button key={p.id} onClick={() => setToIdx(idx)} data-cursor="hover"
                      style={{
                        flex: 1, padding: '10px 8px', borderRadius: 10,
                        background: sel ? 'color-mix(in oklab, var(--accent) 8%, var(--bg-card))' : 'var(--bg-elev)',
                        border: sel ? '1px solid var(--accent)' : '1px solid var(--line)',
                        boxShadow: sel ? '0 0 18px -6px var(--accent-glow)' : 'none',
                        cursor: 'pointer', transition: 'all 0.3s cubic-bezier(.2,.7,.2,1)',
                        textAlign: 'center',
                      }}
                    >
                      <div style={{ fontSize: 15, fontFamily: 'Geist, sans-serif', fontWeight: 700, lineHeight: 1, color: sel ? 'var(--accent)' : 'var(--ink)' }}>{p.price}€</div>
                      <div style={{ fontSize: 10, fontWeight: 600, marginTop: 3, color: sel ? 'var(--ink)' : 'var(--ink-dim)' }}>{p.name}</div>
                      <div style={{ fontSize: 8, marginTop: 3, color: 'var(--accent)', fontFamily: 'Geist Mono', opacity: sel ? 1 : 0.5 }}>{(p.evoRate * 100).toFixed(0)}%</div>
                    </button>
                  );
                })}
              </div>
            </div>
          </div>

          <CalcSlider
            label="Upgrades par mois"
            value={upgrades} min={1} max={30} step={1}
            onChange={setUpgrades}
            format={v => `${v} upgrades`}
          />

          {/* Détail */}
          <div style={{
            marginTop: 4, padding: '14px 16px', borderRadius: 14,
            background: 'var(--bg-elev)', border: '1px solid var(--line)',
          }}>
            <span className="label" style={{ marginBottom: 10, display: 'block' }}>Détail par upgrade</span>
            <DetailRow left={`${fromPack.name} → ${toPack.name}`} right={`+${diff > 0 ? diff : 0} €`} />
            <DetailRow left={`Commission (${(commRate * 100).toFixed(0)}%)`} right={`${commPerUpgrade.toFixed(0)} €`} accent />
            <div style={{
              marginTop: 10, paddingTop: 10,
              borderTop: '1px solid var(--line)',
              display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
            }}>
              <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>Tu encaisses</span>
              <span style={{ fontSize: 20, fontFamily: 'Geist, sans-serif', fontWeight: 800, color: 'var(--accent)', letterSpacing: '-0.02em' }}>{commPerUpgrade.toFixed(0)} €</span>
            </div>
          </div>
        </div>

        {/* ── Résultat ── */}
        <ResultPanel monthly={monthly} yearly={yearly} label="Commission d'évolution" sub={`${(commRate * 100).toFixed(0)}% sur chaque montée de niveau.`} />
      </div>
    </Reveal>
  );
}

/* ═══ Ligne de détail réutilisable ═══ */
function DetailRow({ left, right, accent }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between',
      fontSize: 13, color: 'var(--ink-dim)', marginBottom: 8,
    }}>
      <span>{left}</span>
      <span style={{
        fontFamily: 'Geist Mono',
        color: accent ? 'var(--accent)' : 'var(--ink)',
        fontWeight: accent ? 600 : 400,
      }}>{right}</span>
    </div>
  );
}

/* ═══ Panneau résultat (partagé) ═══ */
function ResultPanel({ monthly, yearly, label, sub }) {
  return (
    <div style={{
      background: 'var(--bg-elev)', borderRadius: 20, padding: 28,
      border: '1px solid var(--line)', position: 'relative', overflow: 'hidden',
      display: 'flex', flexDirection: 'column', justifyContent: 'center',
    }}>
      <div style={{
        position: 'absolute', top: -60, right: -60, width: 240, height: 240,
        background: 'radial-gradient(circle, var(--accent-glow), transparent 70%)',
        filter: 'blur(40px)', pointerEvents: 'none',
      }} />
      <div style={{ position: 'relative' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 4 }}>
          <span className="label">{label}</span>
          {sub && <span style={{ color: 'var(--ink-mute)', fontSize: 11 }}>{sub}</span>}
        </div>
        <div style={{
          fontFamily: 'Geist, sans-serif', fontWeight: 800,
          fontSize: 'clamp(40px, 4.5vw, 64px)',
          lineHeight: 1, letterSpacing: '-0.04em',
          color: 'var(--accent)',
          marginTop: 10,
        }}>
          {monthly.toLocaleString('fr-FR', { maximumFractionDigits: 0 })} €
        </div>
        <div className="mono" style={{ color: 'var(--ink-mute)', marginTop: 4, fontSize: 11 }}>/ mois</div>

        {/* Projections inline */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 20 }}>
          <div style={{ padding: '12px 14px', borderRadius: 12, background: 'var(--bg-card)', border: '1px solid var(--line)' }}>
            <div className="label" style={{ marginBottom: 4, fontSize: 9 }}>6 mois</div>
            <div style={{ fontSize: 22, fontFamily: 'Geist, sans-serif', fontWeight: 800, letterSpacing: '-0.03em' }}>{(monthly * 6).toLocaleString('fr-FR', { maximumFractionDigits: 0 })} €</div>
          </div>
          <div style={{ padding: '12px 14px', borderRadius: 12, background: 'var(--bg-card)', border: '1px solid var(--line)' }}>
            <div className="label" style={{ marginBottom: 4, fontSize: 9 }}>1 an</div>
            <div style={{ fontSize: 22, fontFamily: 'Geist, sans-serif', fontWeight: 800, letterSpacing: '-0.03em' }}>{yearly.toLocaleString('fr-FR', { maximumFractionDigits: 0 })} €</div>
          </div>
        </div>

        <div style={{ marginTop: 20 }}>
          <MagneticBtn variant="primary" href="#pricing">Je veux ces chiffres <span className="btn-arrow"><Icon.Arrow /></span></MagneticBtn>
        </div>
        <p style={{ marginTop: 14, fontSize: 11, color: 'var(--ink-mute)', lineHeight: 1.5 }}>
          Projections indicatives. Les résultats dépendent de ton travail et de ton implication.
        </p>
      </div>
    </div>
  );
}

function CalcSlider({ label, value, min, max, step, onChange, format }) {
  const pct = ((value - min) / (max - min)) * 100;
  return (
    <div style={{ marginBottom: 18 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
        <span className="label">{label}</span>
        <span style={{ fontSize: 24, fontFamily: 'Geist, sans-serif', fontWeight: 800, color: 'var(--accent)', letterSpacing: '-0.02em' }}>{format(value)}</span>
      </div>
      <div style={{ position: 'relative', height: 32 }}>
        <div style={{ position: 'absolute', top: 14, left: 0, right: 0, height: 3, borderRadius: 2, background: 'var(--line)' }} />
        <div style={{ position: 'absolute', top: 14, left: 0, width: `${pct}%`, height: 3, borderRadius: 2, background: 'var(--accent)', boxShadow: '0 0 12px var(--accent-glow)' }} />
        <input
          type="range"
          min={min} max={max} step={step}
          value={value}
          onChange={e => onChange(+e.target.value)}
          data-cursor="hover"
          style={{
            position: 'absolute', inset: 0, width: '100%', height: '100%',
            opacity: 0, cursor: 'pointer',
          }}
        />
        <div style={{
          position: 'absolute', top: 6, left: `${pct}%`, transform: 'translateX(-50%)',
          width: 20, height: 20, borderRadius: '50%',
          background: 'var(--accent)', border: '4px solid var(--bg)',
          boxShadow: '0 0 0 1px var(--accent), 0 0 14px var(--accent-glow)',
          pointerEvents: 'none',
        }} />
      </div>
    </div>
  );
}

Object.assign(window, { Calculator });
