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

const THUMB = '/lp/uploads/miniatures/';

// Les 6 phases VIZION — données réelles de la plateforme
const PHASES = [
  {
    n: '01',
    name: 'Introduction',
    sub: 'Comprendre où tu mets les pieds',
    stats: { modules: 6, chapters: 20, lessons: 79, duration: '5h 43m' },
    desc: 'Tu découvres l\'univers VIZION, le modèle MRR 2.0, le mindset, la fiscalité et les bases du marketing digital.',
    modules: [
      { t: 'Introduction & fonctionnement MRR', img: 'Minia Introv4.jpg', lessons: 14 },
      { t: 'Mindset & État d\'Esprit',          img: 'Minia Mindsetv3.jpg', lessons: 18 },
      { t: 'Fiscalité et déclaration d\'activité', img: 'Minia Fiscalitév2.jpg', lessons: 20 },
      { t: 'L\'opportunité du Marketing digital', img: 'Minia MD.jpg', lessons: 9 },
      { t: 'Création & Optimisation des Réseaux Sociaux', img: 'Minia RS.jpg', lessons: 10 },
      { t: 'Produits digitaux',                  img: 'Minia Produits digitaux.jpg', lessons: 8 },
    ],
  },
  {
    n: '02',
    name: 'Fondation',
    sub: 'Poser les bases de ton business',
    stats: { modules: 3, chapters: 16, lessons: 60, duration: '4h 24m' },
    desc: 'Identifie ta niche, construis une offre qui se vend et maîtrise Canva pour tous tes visuels pros.',
    modules: [
      { t: 'Trouver ta niche & ton client idéal', img: 'Minia ta niche.jpg', lessons: 13 },
      { t: 'Construire ton offre',               img: 'Minia ton offre.jpg', lessons: 18 },
      { t: 'Masterclass CANVA',                  img: 'Minia Design Canva.jpg', lessons: 29 },
    ],
  },
  {
    n: '03',
    name: 'Système',
    sub: 'Créer son tunnel de vente',
    stats: { modules: 3, chapters: 0, lessons: 0, duration: 'Bientôt' },
    desc: 'Tunnel de vente, pages de capture, automatisations — le système qui vend pendant que tu dors.',
    modules: [
      { t: 'Tunnel de vente',                    img: 'Minia Tunnel de vente.jpg', lessons: 0, soon: true },
      { t: 'Stan Store',                         img: 'Minia Stan Store.jpg', lessons: 0, soon: true },
      { t: 'Systeme.io',                         img: 'Minia Systemio.jpg', lessons: 0, soon: true },
    ],
  },
  {
    n: '04',
    name: 'Création de contenu',
    sub: 'Exister en ligne et produire du contenu',
    stats: { modules: 5, chapters: 5, lessons: 29, duration: '2h 35m' },
    desc: 'Algorithme, idées de contenu, scripting, tournage et montage. Tu publies avec régularité et stratégie.',
    modules: [
      { t: 'Stratégie de contenu & Algorithme', img: 'Minia Algo.jpg', lessons: 13 },
      { t: 'Trouver tes Idées de Contenu',       img: 'Minia Inspiration.jpg', lessons: 16 },
      { t: 'Scripting',                          img: 'Minia Scripting.jpg', lessons: 0, soon: true },
      { t: 'Tournage Facecam',                   img: 'Minia Facecam.jpg', lessons: 0, soon: true },
      { t: 'Montage vidéo',                      img: 'Minia Montage.jpg', lessons: 0, soon: true },
    ],
  },
  {
    n: '05',
    name: 'Vente',
    sub: 'Transformer ton audience en clients',
    stats: { modules: 6, chapters: 13, lessons: 54, duration: '3h 55m' },
    desc: 'Psychologie de la vente, closing, lives TikTok, emailing — apprends à vendre naturellement et efficacement.',
    modules: [
      { t: 'Psychologie de la Vente',            img: 'Minia Neurosciences.jpg', lessons: 14 },
      { t: 'Closing',                            img: 'Minia Closing.jpg', lessons: 15 },
      { t: 'Vendre en Live TikTok',              img: 'Minia Tiktok.jpg', lessons: 13 },
      { t: 'Vendre par Email',                   img: 'Minia Emailing.jpg', lessons: 12 },
      { t: 'Story Selling',                      img: 'Minia Story.jpg', lessons: 0, soon: true },
      { t: 'ManyChat',                           img: 'Minia Manychat.jpg', lessons: 0, soon: true },
    ],
  },
  {
    n: '06',
    name: 'Lancement',
    sub: 'Lancement & Scaling',
    stats: { modules: 3, chapters: 0, lessons: 0, duration: 'Bientôt' },
    desc: 'Ton offre en ligne, ta stratégie revendeur activée, ton business qui tourne. Tu deviens autonome.',
    modules: [
      { t: 'Protocole de lancement',             img: 'Minia Protocole.jpg', lessons: 0, soon: true },
      { t: 'Délégation & scaling',               img: 'Minia Délégation.jpg', lessons: 0, soon: true },
      { t: 'Business durable',                   img: 'Minia Business durable.jpg', lessons: 0, soon: true },
    ],
  },
];

/* ═══ Hauteur fixe du panneau droit pour éviter tout layout shift ═══ */
const PANEL_HEIGHT = 620;

function TimelineSection() {
  const { academy } = useLandingStats();
  const [active, setActive] = useState(0);
  const timerRef = useRef(null);
  const [isMobile, setIsMobile] = useState(
    typeof window !== 'undefined' ? window.innerWidth < 768 : false
  );

  // Normaliser "INTRODUCTION" → "Introduction"
  const normalize = (s) =>
    s && s.length > 0 && s === s.toUpperCase()
      ? s.charAt(0) + s.slice(1).toLowerCase()
      : s;

  // Formater une durée en secondes → "Xh Ym" / "Ym" / "Bientôt"
  const formatDuration = (sec) => {
    if (!sec || sec <= 0) return 'Bientôt';
    const h = Math.floor(sec / 3600);
    const m = Math.round((sec % 3600) / 60);
    if (h > 0 && m > 0) return `${h}h ${m}m`;
    if (h > 0) return `${h}h`;
    return `${m}m`;
  };

  // Merge API data (catégorie, titres, leçons, compteurs) dans la structure statique PHASES
  const phases = useMemo(() => {
    if (!academy.phases || academy.phases.length === 0) return PHASES;
    return PHASES.map((phase, i) => {
      const api = academy.phases[i];
      if (!api) return phase;
      const apiName = normalize(api.name);
      // Masquer sub s'il est identique au nom de catégorie (ex: "Poser les bases de ton business")
      const subIsDuplicate =
        phase.sub?.toLowerCase().trim() === apiName?.toLowerCase().trim();
      // Les modules viennent de l'API (titres + leçons réels), image conservée si mapping statique dispo
      const apiModules = api.modules.map((apiMod, j) => {
        const hardcoded = phase.modules[j];
        return {
          t: apiMod.title,
          lessons: apiMod.lessons,
          img: hardcoded?.img,
          soon: apiMod.lessons === 0,
        };
      });
      return {
        ...phase,
        name: apiName,
        sub: subIsDuplicate ? '' : phase.sub,
        stats: {
          ...phase.stats,
          lessons: api.totalLessons,
          modules: api.totalModules,
          duration: formatDuration(api.totalDurationSec),
        },
        modules: apiModules,
      };
    });
  }, [academy.phases]);

  useEffect(() => {
    const check = () => setIsMobile(window.innerWidth < 768);
    window.addEventListener('resize', check, { passive: true });
    return () => window.removeEventListener('resize', check);
  }, []);

  const resetTimer = useCallback(() => {
    if (isMobile) return;
    if (timerRef.current) clearInterval(timerRef.current);
    timerRef.current = setInterval(() => {
      setActive(a => (a + 1) % phases.length);
    }, 6000);
  }, [isMobile]);

  useEffect(() => {
    if (isMobile) {
      if (timerRef.current) clearInterval(timerRef.current);
      return;
    }
    resetTimer();
    return () => clearInterval(timerRef.current);
  }, [isMobile, resetTimer]);

  const handleClick = (i) => {
    setActive(i);
    if (!isMobile) resetTimer();
  };

  const current = phases[active];

  return (
    <section id="parcours" className="section" style={{ position: 'relative' }}>
      <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' }}>De zéro à autonome,</span><br />
            <span className="serif-i" style={{ color: 'var(--accent)', fontWeight: 400 }}>en 6 phases distinctes.</span>
          </h2>
          <p style={{ color: 'var(--ink-dim)', fontSize: 18, maxWidth: 540 }}>
            Chaque phase débloque la suivante. Tu avances à ton rythme, toujours dans l'ordre — pas de zones grises.
          </p>
        </Reveal>

        <div style={{ display: 'grid', gridTemplateColumns: '380px 1fr', gap: 48, alignItems: 'stretch', minHeight: PANEL_HEIGHT }}>

          {/* ── Colonne gauche : 6 phases imposantes ── */}
          <div className="timeline-phases" style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
            {phases.map((p, i) => {
              const isActive = i === active;
              return (
                <button
                  key={i}
                  onClick={() => handleClick(i)}
                  data-cursor="hover"
                  style={{
                    display: 'flex', alignItems: 'center', gap: 16,
                    padding: '20px 18px',
                    textAlign: 'left',
                    background: isActive ? 'var(--bg-card)' : 'transparent',
                    border: isActive ? '1px solid var(--line)' : '1px solid transparent',
                    borderRadius: isActive ? 16 : 16,
                    cursor: 'pointer',
                    transition: 'all 0.35s cubic-bezier(.2,.7,.2,1)',
                    position: 'relative',
                  }}
                >
                  {/* Numéro gros */}
                  <span className="serif" style={{
                    fontSize: 38,
                    lineHeight: 1,
                    color: isActive ? 'var(--accent)' : 'var(--ink-mute)',
                    transition: 'color 0.3s',
                    minWidth: 52,
                    textAlign: 'center',
                    letterSpacing: '-0.02em',
                  }}>{p.n}</span>

                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{
                      fontSize: 20, fontWeight: 600,
                      color: isActive ? 'var(--ink)' : 'var(--ink-dim)',
                      lineHeight: 1.15,
                      transition: 'color 0.3s',
                      letterSpacing: '-0.01em',
                    }}>{p.name}</div>
                    <div className="timeline-phase-sub" style={{
                      fontSize: 12, color: 'var(--ink-mute)',
                      marginTop: 4,
                      whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                    }}>
                      {p.sub}
                    </div>
                  </div>

                  {/* Stats pill */}
                  <div className="timeline-phase-pill" style={{
                    display: 'flex', alignItems: 'center', gap: 6,
                    opacity: isActive ? 1 : 0,
                    transform: isActive ? 'translateX(0)' : 'translateX(-4px)',
                    transition: 'all 0.3s cubic-bezier(.2,.7,.2,1)',
                  }}>
                    <span className="mono" style={{
                      fontSize: 10, color: 'var(--accent)',
                      padding: '4px 8px', borderRadius: 6,
                      background: 'color-mix(in oklab, var(--accent) 10%, transparent)',
                      whiteSpace: 'nowrap',
                    }}>
                      {p.stats.duration}
                    </span>
                  </div>
                </button>
              );
            })}

            {/* Progress bar sous les tabs */}
            <div className="timeline-progress" style={{
              marginTop: 16, height: 3, borderRadius: 2,
              background: 'var(--line)', position: 'relative',
            }}>
              <div style={{
                position: 'absolute', left: 0, top: 0, height: '100%',
                width: `${((active + 1) / phases.length) * 100}%`,
                background: 'var(--accent)', borderRadius: 2,
                boxShadow: '0 0 8px var(--accent-glow)',
                transition: 'width 0.6s cubic-bezier(.2,.7,.2,1)',
              }} />
            </div>
          </div>

          {/* ── Panneau droit : contenu de la phase (hauteur fixe) ── */}
          <div style={{
            background: 'var(--bg-card)',
            border: '1px solid var(--line)',
            borderRadius: 24,
            padding: 32,
            position: 'relative',
            overflow: 'hidden',
            height: '100%',
            minHeight: PANEL_HEIGHT,
            boxSizing: 'border-box',
          }}>
            {/* Glow ambient discret */}
            <div style={{
              position: 'absolute', top: -80, right: -80,
              width: 300, height: 300,
              background: 'radial-gradient(circle, var(--accent-glow), transparent 60%)',
              opacity: 0.18, pointerEvents: 'none',
            }} />

            <div style={{ position: 'relative', height: '100%', display: 'flex', flexDirection: 'column' }}>
              {/* Header */}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16, flexShrink: 0 }}>
                <div>
                  <span className="label" style={{ color: 'var(--accent)' }}>Phase {current.n} / 06</span>
                  <h3 className="serif" style={{
                    fontSize: 36, lineHeight: 1, letterSpacing: '-0.02em',
                    marginTop: 8,
                  }}>
                    {current.name}
                  </h3>
                </div>
                <div style={{ display: 'flex', gap: 8 }}>
                  {[
                    { v: current.stats.modules, l: 'modules' },
                    { v: current.stats.lessons, l: 'leçons' },
                  ].map((s, i) => (
                    <div key={i} style={{
                      padding: '6px 12px', borderRadius: 8,
                      background: 'var(--bg-elev)', border: '1px solid var(--line)',
                      textAlign: 'center',
                    }}>
                      <div className="mono" style={{ fontSize: 16, color: 'var(--accent)', fontWeight: 600, lineHeight: 1 }}>
                        {s.v}
                      </div>
                      <div style={{ fontSize: 9, color: 'var(--ink-mute)', marginTop: 3, fontFamily: 'Geist Mono', letterSpacing: '0.06em' }}>
                        {s.l}
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              <p style={{
                color: 'var(--ink-dim)', fontSize: 14, lineHeight: 1.5,
                marginBottom: 20, flexShrink: 0,
              }}>{current.desc}</p>

              {/* Grille de modules avec miniatures */}
              <div key={active}
                className="timeline-module-grid"
                style={{
                  flex: 1, overflow: 'hidden',
                  display: 'grid',
                  gridTemplateColumns: 'repeat(3, 1fr)',
                  gap: 12,
                  alignContent: 'start',
                  position: 'relative',
                }}>
                {current.modules.map((m, i) => (
                  <div key={i} className="module-card" style={{
                    borderRadius: 14,
                    background: 'var(--bg-elev)',
                    border: '1px solid var(--line)',
                    overflow: 'hidden',
                    animation: `moduleIn 0.9s cubic-bezier(.16,.84,.44,1) ${i * 0.12}s both`,
                    transition: 'all 0.35s cubic-bezier(.2,.7,.2,1)',
                    boxShadow: '0 2px 8px -2px rgba(0,0,0,0.12)',
                    position: 'relative',
                  }}>
                    {/* Miniature */}
                    <div style={{
                      aspectRatio: '16 / 9',
                      overflow: 'hidden',
                      position: 'relative',
                      background: 'var(--bg)',
                    }}>
                      {m.img && (
                      <img
                        src={encodeURI(THUMB + m.img)}
                        alt={m.t}
                        loading="lazy"
                        style={{
                          width: '100%', height: '100%',
                          objectFit: 'cover',
                          display: 'block',
                          opacity: m.soon ? 0.4 : 1,
                          transition: 'transform 0.35s ease',
                        }}
                        onMouseEnter={e => e.currentTarget.style.transform = 'scale(1.06)'}
                        onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}
                      />
                      )}
                      {m.soon && (
                        <div style={{
                          position: 'absolute', inset: 0,
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                        }}>
                          <span className="mono" style={{
                            fontSize: 9, color: 'var(--ink-mute)',
                            padding: '3px 8px', borderRadius: 6,
                            background: 'color-mix(in oklab, var(--bg) 80%, transparent)',
                            backdropFilter: 'blur(6px)',
                            letterSpacing: '0.08em',
                            textTransform: 'uppercase',
                          }}>Bientôt</span>
                        </div>
                      )}
                    </div>
                    {/* Info avec badge leçons amélioré */}
                    <div style={{ padding: '12px 13px' }}>
                      <div style={{
                        fontSize: 11.5, fontWeight: 600,
                        color: 'var(--ink)',
                        lineHeight: 1.25,
                        display: '-webkit-box',
                        WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
                        overflow: 'hidden',
                        marginBottom: m.lessons > 0 ? 6 : 0,
                      }}>
                        {m.t}
                      </div>
                      {m.lessons > 0 ? (
                        <div style={{
                          display: 'inline-flex', alignItems: 'center', gap: 4,
                          padding: '3px 8px', borderRadius: 6,
                          background: 'color-mix(in oklab, var(--accent) 12%, var(--bg))',
                          border: '1px solid color-mix(in oklab, var(--accent) 25%, transparent)',
                        }}>
                          <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--accent)' }} />
                          <span className="mono" style={{ fontSize: 9, color: 'var(--accent)', fontWeight: 500 }}>
                            {m.lessons} leçons
                          </span>
                        </div>
                      ) : m.soon ? (
                        <div style={{
                          display: 'inline-flex', alignItems: 'center', gap: 4,
                          padding: '3px 8px', borderRadius: 6,
                          background: 'var(--bg)',
                          border: '1px dashed var(--line-strong)',
                        }}>
                          <span className="mono" style={{ fontSize: 9, color: 'var(--ink-mute)', fontWeight: 500 }}>
                            Bientôt
                          </span>
                        </div>
                      ) : null}
                    </div>

                    {/* Indicateur de progression subtil */}
                    <div style={{
                      position: 'absolute', bottom: 0, left: 0, right: 0, height: 2,
                      background: 'var(--line)',
                    }}>
                      <div style={{
                        width: m.soon ? '0%' : '100%', height: '100%',
                        background: 'linear-gradient(90deg, var(--accent), var(--accent-glow))',
                        transition: 'width 0.6s ease',
                      }} />
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>

      <style>{`
        @keyframes moduleIn {
          from { opacity: 0; transform: translateY(16px); filter: blur(8px); }
          to   { opacity: 1; transform: translateY(0);   filter: blur(0); }
        }
        .module-card:hover {
          transform: translateY(-3px) !important;
          border-color: color-mix(in oklab, var(--accent) 40%, var(--line)) !important;
          box-shadow: 0 8px 24px -6px rgba(45,205,147,0.15) !important;
        }
      `}</style>
    </section>
  );
}

Object.assign(window, { TimelineSection });
