const { useRef, useEffect, useState } = React;
const { Reveal, Icon, useLandingStats } = window;

const PILLARS = [
  {
    n: '01',
    eyebrow: 'Formation',
    title: 'Une vraie plateforme d\'apprentissage.',
    desc: '26 modules structurés en 6 phases. Une progression claire, des quiz, des outils pour optimiser la pédagogie — pour que chaque heure passée te rapproche d\'un vrai business.',
    bullets: ['26 modules vidéo', '20 h de formation', '13 quiz'],
    visual: 'academy',
  },
  {
    n: '02',
    eyebrow: 'Revenus',
    title: 'Un vrai système MRR, intégré à la plateforme.',
    desc: 'Sur chaque vente, tu gardes 100% du prix. Et quand tes clients évoluent vers un pack supérieur, tu touches une commission passive. Deux flux de revenus qui travaillent en parallèle.',
    bullets: ['100% sur tes ventes', 'Commission d\'évolution 25 → 75 %', 'Paiement hebdo'],
    visual: 'revenue',
    invert: true,
  },
  {
    n: '03',
    eyebrow: 'Communauté',
    title: 'Une communauté qui fait vraiment avancer.',
    desc: 'Un forum structuré, des catégories claires, des wins partagés au quotidien. Je suis présent chaque jour pour répondre à tes questions et débloquer ce qui coince.',
    bullets: ['Forum structuré', 'Réponses du formateur', 'Mentorat 1:1'],
    visual: 'community',
  },
];

function Pillars() {
  const { academy } = useLandingStats();
  const hours = academy.totalHours || 20;
  const mods = academy.modulesCount || 26;
  const academyBullets = [
    `${mods} modules vidéo`,
    `${hours} h de formation`,
    `${academy.quizCount || 13} quiz`,
  ];
  const academyDesc = `${mods} modules structurés en 6 phases. Une progression claire, des quiz, des outils pour optimiser la pédagogie — pour que chaque heure passée te rapproche d'un vrai business.`;
  return (
    <section id="platform" className="section section-soft">
      <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' }}>Trois piliers,</span><br />
            <span className="serif-i" style={{ color: 'var(--accent)', fontWeight: 400 }}>un seul système.</span>
          </h2>
          <p style={{ color: 'var(--ink-dim)', fontSize: 18, maxWidth: 540 }}>
            Tu apprends, tu produis, tu distribues — sans jamais changer d'outil. Chaque pilier prépare le suivant.
          </p>
        </Reveal>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {PILLARS.map((p, i) => (
            <PillarCard
              key={i}
              {...p}
              bullets={p.visual === 'academy' ? academyBullets : p.bullets}
              desc={p.visual === 'academy' ? academyDesc : p.desc}
              index={i}
              total={PILLARS.length}
            />
          ))}
        </div>
      </div>
    </section>
  );
}

function PillarCard({ n, eyebrow, title, desc, bullets, visual, index, invert }) {
  const textContent = (
    <div className={invert ? 'pillar-text-invert' : ''} style={invert ? { textAlign: 'right' } : {}}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 20, flexDirection: invert ? 'row-reverse' : 'row' }}>
        <span className="mono" style={{ fontSize: 13, color: 'var(--accent)' }}>{n}</span>
        <span style={{ height: 1, width: 40, background: 'var(--line-strong)' }}></span>
        <span className="label">{eyebrow}</span>
      </div>
      <h3 className="h3" style={{ marginBottom: 16, maxWidth: 480, marginLeft: invert ? 'auto' : 0 }}>{title}</h3>
      <p style={{ color: 'var(--ink-dim)', marginBottom: 22, maxWidth: 480, marginLeft: invert ? 'auto' : 0 }}>{desc}</p>
      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', justifyContent: invert ? 'flex-end' : 'flex-start' }}>
        {bullets.map((b, i) => (
          <span key={i} className="chip" style={{ background: 'var(--bg-elev)', color: 'var(--ink)', textTransform: 'none', letterSpacing: 0, fontSize: 12, fontFamily: 'Geist, sans-serif', padding: '7px 14px' }}>
            <Icon.Check size={11} />{b}
          </span>
        ))}
      </div>
    </div>
  );
  const visualContent = (
    <div style={{ position: 'relative', height: 320, overflow: 'hidden', borderRadius: 16 }}>
      {visual === 'academy' && <AcademyVisual />}
      {visual === 'revenue' && <RevenueVisual />}
      {visual === 'community' && <CommunityVisual />}
    </div>
  );

  return (
    <Reveal delay={index + 1}>
      <div className="card pillar-card" style={{ display: 'grid', gridTemplateColumns: invert ? '1fr 1.4fr' : '1.4fr 1fr', gap: 40, padding: '36px 44px', minHeight: 280, alignItems: 'center' }}>
        {invert ? (
          <>{visualContent}{textContent}</>
        ) : (
          <>{textContent}{visualContent}</>
        )}
      </div>
    </Reveal>
  );
}

/* Helper curseur local — même logique que demo.jsx */
function acadCursorTipFor(targetEl, rootEl) {
  if (!targetEl || !rootEl) return { x: 0, y: 0 };
  const a = targetEl.getBoundingClientRect();
  const b = rootEl.getBoundingClientRect();
  return { x: (a.left - b.left) + a.width / 2 - 2, y: (a.top - b.top) + a.height / 2 - 2 };
}

/* Academy: curseur animé qui coche les phases une par une */
function AcademyVisual() {
  const { academy } = useLandingStats();
  // Normaliser la casse : "INTRODUCTION" → "Introduction"
  const normalizeName = (s) =>
    s.length > 0 && s === s.toUpperCase()
      ? s.charAt(0) + s.slice(1).toLowerCase()
      : s;
  const apiPhases = academy.phases ?? [];
  const phases = apiPhases.length > 0
    ? apiPhases.map((p, i) => ({ n: i + 1, name: normalizeName(p.name) }))
    : [
        { n: 1, name: 'Introduction' },
        { n: 2, name: 'Poser les bases de ton business' },
        { n: 3, name: 'Créer son tunnel de vente' },
        { n: 4, name: 'Exister en ligne et produire du contenu' },
        { n: 5, name: 'Transformer ton audience en clients' },
        { n: 6, name: 'Lancement & Scaling' },
      ];

  const [checked, setChecked] = useState(() => new Array(phases.length).fill(false));
  const [cursor, setCursor]   = useState({ x: 200, y: 10 });
  const [clicking, setClicking] = useState(false);
  const containerRef = useRef(null);
  const rowRefs = useRef([]);

  useEffect(() => {
    let cancelled = false;
    const sleep = (ms) => new Promise(r => setTimeout(r, ms));
    const run = async () => {
      while (!cancelled) {
        setChecked(new Array(phases.length).fill(false));
        await sleep(800);
        for (let i = 0; i < phases.length; i++) {
          if (cancelled) return;
          const pos = acadCursorTipFor(rowRefs.current[i], containerRef.current);
          setCursor(pos);
          await sleep(700);
          setClicking(true);
          await sleep(150);
          setChecked(prev => { const n = [...prev]; n[i] = true; return n; });
          setClicking(false);
          await sleep(380);
        }
        await sleep(2200);
      }
    };
    run();
    return () => { cancelled = true; };
  }, []);

  return (
    <div ref={containerRef} style={{ background: 'var(--bg-elev)', borderRadius: 16, padding: 20, border: '1px solid var(--line)', position: 'relative', overflow: 'hidden', height: '100%' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <span className="label">Parcours · {academy.totalHours || 20} h</span>
        <span className="mono" style={{ fontSize: 11, color: 'var(--accent)' }}>{academy.modulesCount || 26} modules</span>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {phases.map((m, i) => {
          const done = checked[i];
          return (
            <div key={i}
              ref={el => { rowRefs.current[i] = el; }}
              style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '10px 12px', borderRadius: 10,
                background: done ? 'color-mix(in oklab, var(--accent) 9%, var(--bg-card))' : 'var(--bg-card)',
                border: done ? '1px solid color-mix(in oklab, var(--accent) 32%, transparent)' : '1px solid var(--line)',
                transition: 'all 0.3s cubic-bezier(.2,.7,.2,1)',
              }}>
              <span style={{
                width: 22, height: 22, borderRadius: 6, flexShrink: 0,
                background: done ? 'var(--accent)' : 'var(--bg-elev)',
                border: done ? 'none' : '1.5px solid var(--line-strong)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: '#fff',
                transition: 'all 0.25s ease',
                transform: done ? 'scale(1.1)' : 'scale(1)',
                boxShadow: done ? '0 0 0 3px color-mix(in oklab, var(--accent) 22%, transparent)' : 'none',
              }}>
                {done && <Icon.Check size={11} />}
              </span>
              <span style={{
                fontSize: 13, flex: 1,
                color: done ? 'var(--ink)' : 'var(--ink-dim)',
                fontWeight: done ? 500 : 400,
                transition: 'color 0.3s ease',
              }}>{m.name}</span>
              {done && <span className="mono" style={{ fontSize: 10, color: 'var(--accent)' }}>✓</span>}
            </div>
          );
        })}

      </div>

      {/* Curseur animé */}
      <div style={{
        position: 'absolute', top: cursor.y, left: cursor.x,
        width: 20, height: 22, pointerEvents: 'none', zIndex: 30,
        filter: 'drop-shadow(0 3px 6px rgba(0,0,0,0.4))',
        transition: 'all 0.55s cubic-bezier(.4,.2,.2,1)',
      }}>
        <svg width="20" height="22" viewBox="0 0 20 22">
          <path d="M2 2 L9 17 L11.5 11 L18 9 Z" fill="#ffffff" stroke="#0a0a0b" strokeWidth="1.2" strokeLinejoin="round" />
        </svg>
        {clicking && (
          <div style={{
            position: 'absolute', top: -18, left: -18,
            width: 40, height: 40, borderRadius: '50%',
            border: '2px solid var(--accent)',
            opacity: 0, animation: 'acadClickRing 0.5s ease-out',
          }} />
        )}
      </div>

      <style>{`@keyframes acadClickRing{0%{opacity:0.8;transform:scale(0.3)}100%{opacity:0;transform:scale(1.4)}}`}</style>
    </div>
  );
}

/* Revenue: live ticker — ventes + commissions avec compteur animé */
function RevenueVisual() {
  const EVENTS = [
    { id: 0, label: 'Vente Starter',           amt: 199,  src: 'Stripe',  tinted: false, group: 'sale' },
    { id: 1, label: 'Vente Premium',          amt: 799,  src: 'Revolut', tinted: false, group: 'sale' },
    { id: 2, label: 'Commission Starter→Pro', amt: 150,  src: 'Auto',    tinted: true,  group: 'comm' },
    { id: 3, label: 'Commission Pro→Premium', amt: 300,  src: 'Auto',    tinted: true,  group: 'comm' },
  ];

  const [visible, setVisible] = useState([]);
  const [displayTotal, setDisplayTotal] = useState(0);
  const animRef = useRef(null);

  /* Anime le compteur de `from` vers `to` en ~500ms */
  const animateTotal = (from, to) => {
    if (animRef.current) cancelAnimationFrame(animRef.current);
    const duration = 500;
    const start = performance.now();
    const tick = (now) => {
      const t = Math.min(1, (now - start) / duration);
      const ease = 1 - Math.pow(1 - t, 3);
      setDisplayTotal(Math.round(from + (to - from) * ease));
      if (t < 1) animRef.current = requestAnimationFrame(tick);
    };
    animRef.current = requestAnimationFrame(tick);
  };

  useEffect(() => {
    let cancelled = false;
    const sleep = (ms) => new Promise(r => setTimeout(r, ms));
    const run = async () => {
      while (!cancelled) {
        // Apparition un par un
        let runningTotal = 0;
        for (let i = 0; i < EVENTS.length; i++) {
          if (cancelled) return;
          await sleep(700);
          setVisible(prev => [...prev, EVENTS[i].id]);
          const prev = runningTotal;
          runningTotal += EVENTS[i].amt;
          animateTotal(prev, runningTotal);
        }
        // Pause courte une fois tout affiché
        await sleep(1800);
        // Disparition un par un du plus ancien au plus récent
        for (let i = 0; i < EVENTS.length; i++) {
          if (cancelled) return;
          await sleep(300);
          setVisible(prev => prev.filter(id => id !== EVENTS[i].id));
          const remaining = EVENTS.slice(i + 1).reduce((s, e) => s + e.amt, 0);
          animateTotal(runningTotal, remaining);
          runningTotal = remaining;
        }
        // Redémarre immédiatement
        await sleep(0);
      }
    };
    run();
    return () => { cancelled = true; if (animRef.current) cancelAnimationFrame(animRef.current); };
  }, []);

  return (
    <div style={{ background: 'var(--bg-elev)', borderRadius: 16, padding: 20, border: '1px solid var(--line)', height: '100%', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      {/* Total animé */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 16 }}>
        <div>
          <span className="label" style={{ display: 'block', marginBottom: 4 }}>Mes revenus aujourd'hui</span>
          <span style={{ fontFamily: 'Geist Mono', fontSize: 32, fontWeight: 500, color: 'var(--ink)', letterSpacing: '-0.02em' }}>
            {displayTotal.toLocaleString('fr-FR')} €
          </span>
          <span style={{ fontSize: 11, color: 'var(--ink-mute)', marginTop: 2, display: 'block' }}>+{visible.length} transactions</span>
        </div>
        <span className="mono" style={{ fontSize: 11, color: 'var(--accent)', display: 'flex', alignItems: 'center', gap: 5 }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)', display: 'inline-block', animation: 'breathe 1.4s infinite' }} />
          LIVE
        </span>
      </div>

      {/* Lignes d'événements dans un cadre unique */}
      <div style={{
        display: 'flex', flexDirection: 'column', gap: 0,
        borderRadius: 12, border: '1px solid var(--line-strong)',
        background: 'var(--bg-card)', overflow: 'hidden'
      }}>
        {EVENTS.map((e, idx) => {
          const shown = visible.includes(e.id);
          const isLast = idx === EVENTS.length - 1;
          return (
            <div key={e.id} style={{
              display: 'grid', gridTemplateColumns: '8px 1fr auto', gap: 10, alignItems: 'center',
              padding: '10px 12px', fontSize: 12,
              background: e.tinted ? 'color-mix(in oklab, var(--accent) 8%, var(--bg-card))' : 'transparent',
              borderBottom: isLast ? 'none' : '1px solid var(--line)',
              opacity: shown ? 1 : 0,
              transform: shown ? 'translateX(0)' : 'translateX(20px)',
              filter: shown ? 'blur(0px)' : 'blur(4px)',
              transition: 'opacity 0.4s ease, transform 0.4s ease, filter 0.4s ease',
            }}>
              <span style={{ width: 7, height: 7, borderRadius: '50%', background: e.tinted ? 'var(--accent)' : 'var(--ink-mute)', display: 'inline-block' }} />
              <span style={{ color: 'var(--ink-dim)' }}>{e.label}</span>
              <span className="mono" style={{ color: 'var(--accent)', fontWeight: 600 }}>+{e.amt.toLocaleString('fr-FR')} €</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* Community: messages statiques, reply toujours visible, typing animé, emojis pulsés */
function CommunityVisual() {
  // Liste figée : question en haut (avec reply) + 2 wins en dessous
  const MSGS = [
    {
      u: 'clem_t',
      t: 'Mon offre convertit pas, une idée ?',
      tag: 'question',
      reply: { u: 'rémy_digit', t: 'Partage le lien, je fais un retour en DM ce soir.' },
    },
    {
      u: 'emil_m',
      t: '1 000 € de commissions ce mois-ci',
      emoji: '�',
      tag: 'wins',
      reply: null,
    },
    {
      u: 'sofia_v',
      t: 'Script IA → 340k vues en 3 jours',
      emoji: '�',
      tag: 'wins',
      reply: null,
    },
  ];

  // Seule animation : typing indicator qui tourne sur 5 users différents
  const [typing, setTyping] = useState(true);
  const typingUser = useRef('zoe_dg');

  useEffect(() => {
    const TYPING_USERS = ['zoe_dg', 'marc_l', 'ava_r', 'hugo_b', 'nina_s'];
    let cancelled = false;
    const cycle = () => {
      if (cancelled) return;
      setTyping(false);
      setTimeout(() => {
        if (cancelled) return;
        typingUser.current = TYPING_USERS[Math.floor(Math.random() * TYPING_USERS.length)];
        setTyping(true);
      }, 600);
    };
    const id = setInterval(cycle, 4000);
    return () => { cancelled = true; clearInterval(id); };
  }, []);

  const tagColor = (tag) => tag === 'question'
    ? { bg: 'color-mix(in oklab, #f59e0b 16%, transparent)', fg: '#f59e0b' }
    : { bg: 'color-mix(in oklab, var(--accent) 15%, transparent)', fg: 'var(--accent)' };

  return (
    <div style={{ background: 'var(--bg-elev)', borderRadius: 16, padding: 20, border: '1px solid var(--line)', display: 'flex', flexDirection: 'column', gap: 10 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span className="label">Forum · #communauté</span>
        <span className="mono" style={{ fontSize: 11, color: 'var(--ink-mute)' }}>
          <span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)', marginRight: 6, animation: 'breathe 1.4s infinite' }}></span>
          2 431 en ligne
        </span>
      </div>

      {/* Typing indicator — slot toujours rendu (opacity toggle), hauteur fixe */}
      <div style={{
        height: 36,
        padding: '10px 12px',
        background: 'color-mix(in oklab, var(--accent) 8%, var(--bg-card))',
        border: '1px dashed var(--accent)', borderRadius: 10,
        display: 'flex', alignItems: 'center', gap: 10,
        fontSize: 11, color: 'var(--accent)',
        opacity: typing ? 1 : 0,
        transition: 'opacity 0.3s ease',
        overflow: 'hidden',
        flexShrink: 0,
      }}>
        <span className="mono">@{typingUser.current}</span>
        <span style={{ display: 'flex', gap: 3 }}>
          {[0, 0.2, 0.4].map((d, k) => (
            <span key={k} style={{ width: 4, height: 4, borderRadius: '50%', background: 'var(--accent)', animation: `typingDot 1.2s infinite`, animationDelay: `${d}s` }} />
          ))}
        </span>
        <span style={{ color: 'var(--ink-mute)', fontSize: 10 }}>est en train d'écrire…</span>
      </div>

      {/* Messages statiques — question + reply Rémy Digit visible dès le rendu, puis 2 wins */}
      {MSGS.map((m, i) => {
        const tc = tagColor(m.tag);
        return (
          <div key={m.u} style={{
            opacity: 1 - i * 0.08,
            display: 'flex', flexDirection: 'column', gap: 6,
            flexShrink: 0,
          }}>
            <div style={{
              padding: 12, borderRadius: 10,
              background: 'var(--bg-card)', border: '1px solid var(--line)',
              display: 'grid', gridTemplateColumns: '28px 1fr auto', gap: 10, fontSize: 12,
            }}>
              <div style={{ width: 28, height: 28, borderRadius: '50%', background: `oklch(0.6 0.15 ${(m.u.charCodeAt(0) * 7) % 360})` }} />
              <div>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                  <span style={{ fontWeight: 500 }}>@{m.u}</span>
                  <span className="mono" style={{ fontSize: 9, padding: '2px 6px', borderRadius: 4, background: tc.bg, color: tc.fg }}>#{m.tag}</span>
                </div>
                <div style={{ color: 'var(--ink-dim)', marginTop: 2 }}>
                  {m.t}
                  {m.emoji && (
                    <span style={{
                      display: 'inline-block',
                      marginLeft: 6,
                      animation: `emojiPulse 2.4s ease-in-out ${i * 0.4}s infinite`,
                      transformOrigin: 'center',
                    }}>{m.emoji}</span>
                  )}
                </div>
              </div>
              <div className="mono" style={{ fontSize: 10, color: 'var(--accent)' }}>
                {m.tag === 'question' ? '💬 3' : '♡ ' + (12 + (m.u.charCodeAt(0) % 30))}
              </div>
            </div>

            {/* Réponse du formateur (affichée en permanence pour le 1er message) */}
            {m.reply && (
              <div style={{
                marginLeft: 22,
                padding: '10px 12px', borderRadius: 10,
                background: 'color-mix(in oklab, var(--accent) 8%, var(--bg-card))',
                border: '1px solid color-mix(in oklab, var(--accent) 35%, transparent)',
                display: 'grid', gridTemplateColumns: '24px 1fr', gap: 10, fontSize: 12,
                position: 'relative',
                flexShrink: 0,
              }}>
                <div style={{
                  width: 24, height: 24, borderRadius: '50%',
                  background: 'var(--accent)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  color: '#fff', fontSize: 10, fontWeight: 700,
                  boxShadow: '0 0 0 2px color-mix(in oklab, var(--accent) 25%, transparent)',
                }}>R</div>
                <div style={{ minWidth: 0 }}>
                  <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                    <span style={{ fontWeight: 500, color: 'var(--accent)' }}>@{m.reply.u}</span>
                    <span className="mono" style={{ fontSize: 9, padding: '1px 6px', borderRadius: 4, background: 'var(--accent)', color: '#fff' }}>FORMATEUR</span>
                  </div>
                  <div style={{ color: 'var(--ink)', marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.reply.t}</div>
                </div>
              </div>
            )}
          </div>
        );
      })}

      <style>{`
        @keyframes fadeInUp{from{opacity:0;transform:translateY(10px);filter:blur(6px)}to{opacity:1;transform:translateY(0);filter:blur(0)}}
        @keyframes typingDot{0%,60%,100%{opacity:0.3;transform:translateY(0)}30%{opacity:1;transform:translateY(-2px)}}
        @keyframes emojiPulse{
          0%, 100% { transform: scale(1) rotate(0deg); }
          25% { transform: scale(1.25) rotate(-8deg); }
          50% { transform: scale(1.1) rotate(6deg); }
          75% { transform: scale(1.2) rotate(-4deg); }
        }
      `}</style>
    </div>
  );
}

Object.assign(window, { Pillars });
