// education.jsx — 服務 → 全自動內容行銷漏斗 (Automated Content Marketing Funnel): any industry, and it grows the person's own IP. The samples are a teacher's.
// Built from a Latin-American teacher's funnel: AI-clone shorts → comment keyword → automatic DM → evergreen webinar 3×/day →
// 24/7 AI sales on WhatsApp/LINE with an instalment link → free community → weekly report, back to content.
// The "people walk out, an AI takes each layer" animation is ported from the AISO deck (slide 30).
// No client name, prices, contract terms or vendor names. Copy: t.products.edu. Route: #/services/content-marketing-funnel (the old #/services/education-ai-funnel still opens it).
// Videos in assets/edu/ are the teacher's real samples, shown without his name (Alex approved, 2026-12-04).

const EDU_COLORS = ['#3b82f6', '#6366f1', '#f59e0b', '#22c55e', '#a78bfa'];
const eduFmt = (n) => Math.round(n).toLocaleString('en-US');
const eduRnd = (a, b) => a + Math.random() * (b - a);
const eduCalm = () => window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;

// Eases a number toward its target; ms = 0 jumps at once.
function useTween(target, ms = 900) {
  const [v, setV] = useState(target);
  const cur = useRef(target);
  useEffect(() => {
    if (!ms || eduCalm()) { cur.current = target; setV(target); return; }
    let raf, t0; const from = cur.current;
    const tick = (now) => {
      t0 = t0 || now;
      const k = Math.min(1, (now - t0) / ms), e = 1 - Math.pow(1 - k, 3);
      cur.current = from + (target - from) * e; setV(cur.current);
      if (k < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target, ms]);
  return v;
}

// True while the element is on screen (unlike useInView, it turns false again when it leaves).
function useOnScreen(ref, threshold = 0.25) {
  const [on, setOn] = useState(false);
  useEffect(() => {
    const io = new IntersectionObserver(([e]) => setOn(e.isIntersecting), { threshold });
    if (ref.current) io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return on;
}

// A sample video: plays only while on screen, tap to hear it (turning one on mutes the others).
function EduVideo({ name, className }) {
  const box = useRef(null), vid = useRef(null);
  const on = useOnScreen(box, 0.35);
  const [muted, setMuted] = useState(true);
  useEffect(() => {
    const v = vid.current; if (!v) return;
    if (on) v.play().catch(() => {}); else v.pause();
  }, [on]);
  useEffect(() => {
    const off = (e) => { if (e.detail !== vid.current) { vid.current.muted = true; setMuted(true); } };
    window.addEventListener('edu-sound', off);
    return () => window.removeEventListener('edu-sound', off);
  }, []);
  const toggle = () => {
    const v = vid.current, next = !v.muted;
    v.muted = next; setMuted(next);
    if (!next) { window.dispatchEvent(new CustomEvent('edu-sound', { detail: v })); v.play().catch(() => {}); }
  };
  return (
    <div ref={box} className={'ev ' + (className || '')} onClick={toggle}>
      <video ref={vid} src={`assets/edu/${name}.mp4`} poster={`assets/edu/${name}.jpg`} muted loop playsInline preload="none" />
      <button type="button" className="ev-snd" aria-label={muted ? 'Sound on' : 'Sound off'}>{muted ? '🔇' : '🔊'}</button>
    </div>
  );
}

// Hero: the funnel runs by itself. A light moves down five tiers, chat bubbles pop beside the lit tier,
// each tier's count ticks up, and revenue grows when a sale lands.
function EduFunnel({ h }) {
  const ref = useRef(null);
  const on = useOnScreen(ref, 0.2);
  const N = h.tiers.length;
  const [step, setStep] = useState(0);
  const [nums, setNums] = useState([128400, 3216, 846, 92, 412]);
  const [rev, setRev] = useState(h.rev.base);
  useEffect(() => {
    if (!on || eduCalm()) return;
    const id = setInterval(() => setStep((s) => (s + 1) % N), 2800);
    return () => clearInterval(id);
  }, [on]);
  useEffect(() => {
    const add = [eduRnd(900, 2400), eduRnd(18, 60), eduRnd(4, 14), eduRnd(1, 3), eduRnd(2, 6)];
    setNums((n) => n.map((x, i) => (i <= step ? x + add[i] : x)));
    if (step === 3) setRev((r) => r + eduRnd(h.rev.step[0], h.rev.step[1]) * 3);
  }, [step]);
  const shownRev = useTween(rev, 1200);
  return (
    <div ref={ref} className="ef">
      <span className="ef-ex">{h.example}</span>
      <div className="ef-top">
        <div className="ef-plats l">{['ig', 'tiktok', 'yt'].map((k) => <i key={k} className="ic">{IC[k]}</i>)}</div>
        <div className="ef-phone"><EduVideo name="el-hoyo" /></div>
        <div className="ef-plats r">{['fb', 'threads', 'linkedin'].map((k) => <i key={k} className="ic">{IC[k]}</i>)}</div>
      </div>
      <div className="ef-tiers" style={{ '--step': step }} aria-hidden="true">
        {h.tiers.map((t, i) => (
          <div key={i} className={'ef-tier' + (i === step ? ' on' : '')} style={{ '--c': EDU_COLORS[i], '--w': `${100 - i * 11}%` }}>
            <i className="ic">{IC[t.i]}</i><b>{t.n}</b>
            <span className="ef-num">{eduFmt(nums[i])}<small>{t.u}</small></span>
          </div>
        ))}
        <div className="ef-bubbles" key={step}>
          {h.bubbles[step].map((b, k) => (
            <div key={k} className={'ef-bub ' + (k ? 'r ' : 'l ') + (b.k || '')} style={{ animationDelay: `${k * 0.9}s` }}>
              <span className="ef-av" style={{ background: b.c }}><i className="ic">{IC[b.i]}</i></span>
              <div><strong>{b.w}</strong>{b.t}</div>
            </div>
          ))}
        </div>
      </div>
      <div className={'ef-money' + (step === 3 ? ' grow' : '')}>
        <small>{h.revLabel}</small><b>{h.rev.prefix}{eduFmt(shownRev)}</b>
      </div>
    </div>
  );
}

// Your talks become your AI clone's daily shorts: the real recorded webinar on the left, three AI-clone shorts on the right.
function EduClone({ c }) {
  return (
    <>
      <div className="ec">
        <figure className="ec-src">
          <EduVideo name="webinar" className="wide" />
          <figcaption>{c.srcLabel}</figcaption>
          <div className="ec-chips">{c.chips.map((x, i) => <span key={i}>{x}</span>)}</div>
        </figure>
        <div className="ec-arrow" aria-hidden="true"><i className="ic">{IC.sparkles}</i></div>
        <figure className="ec-out">
          <div className="ec-phones">{['el-hoyo', 'ia-resultados', 'ubicacion'].map((n) => <EduVideo key={n} name={n} className="tall" />)}</div>
          <figcaption>{c.outLabel}</figcaption>
        </figure>
      </div>
      <p className="why-note">{c.note}</p>
    </>
  );
}

// The six layers, one lit after another, with the loop back to the top.
function EduStages({ s }) {
  return (
    <div className="es">
      <ol className="es-list">
        {s.list.map((it, i) => (
          <li key={i} style={{ '--c': EDU_COLORS[i] || '#0d9488', animationDelay: `${i * 0.6}s` }}>
            <div className="es-top"><span className="es-n">{String(i + 1).padStart(2, '0')}</span><i className="ic">{IC[it.i]}</i><b>{it.n}</b></div>
            <p>{it.d}</p>
            <div className="es-ch">{it.ch.map((k) => <i key={k} className="ic">{IC[k]}</i>)}</div>
          </li>
        ))}
      </ol>
      <div className="es-loop"><i className="ic">{IC.loop}</i>{s.loop}</div>
    </div>
  );
}

// Ported from the AISO deck: every layer starts with busy people (sweating); then they walk out to the right,
// an AI takes each layer, one person (you) stays, and the counters fall. 3 s people, 1 s change, 3 s AI, on a loop.
const EDU_HOURS = 40;
function EduXform({ x }) {
  const ref = useRef(null);
  const on = useOnScreen(ref, 0.3);
  const [ai, setAi] = useState(false);
  const [snap, setSnap] = useState(false);
  useEffect(() => {
    if (!on) return;
    if (eduCalm()) { setAi(true); return; }
    let t1, t2, alive = true;
    const cycle = () => {
      setSnap(true); setAi(false);
      requestAnimationFrame(() => requestAnimationFrame(() => alive && setSnap(false)));
      t1 = setTimeout(() => alive && setAi(true), 3000);
      t2 = setTimeout(() => alive && cycle(), 7500);
    };
    cycle();
    return () => { alive = false; clearTimeout(t1); clearTimeout(t2); };
  }, [on]);
  const total = x.layers.reduce((u, l) => u + l[3], 0);
  const e = useTween(ai ? 1 : 0, ai ? 1000 : 0);
  const people = Math.round(total + (1 - total) * e);
  const save = Math.round((1 - 1 / total) * 100 * e);
  const hours = Math.round(EDU_HOURS + (168 - EDU_HOURS) * e);
  return (
    <div ref={ref} className={'xf' + (ai ? ' ai' : '') + (snap ? ' snap' : '')}>
      <div className="section-head">
        <div className="eyebrow">{x.eyebrow}</div>
        <h2 className="h-1">{x.title}</h2>
        <p className="lede xf-body">{x.body}</p>
      </div>
      <div className="xf-layers">
        {x.layers.map(([name, ic, what, n, agent], li) => (
          <div key={li} className="xf-layer" style={{ '--n': li, '--c': EDU_COLORS[li] }}>
            <div className="xf-bar"><i className="ic">{IC[ic]}</i>{name}</div>
            <div className="xf-cell">
              <div className="xf-hum">
                <span className="xf-ppl">{Array.from({ length: n }, (_, p) => <i key={p} className="ic" style={{ '--p': p + li, '--q': n - 1 - p }}>{IC.user}</i>)}</span>
                <small>{what}</small>
              </div>
              <span className="xf-ag"><i className="ic">{IC.robot}</i>{agent}</span>
              {li === x.layers.length - 1 && <span className="xf-keep"><i className="ic">{IC.user}</i>{x.keep}</span>}
            </div>
          </div>
        ))}
      </div>
      <div className="xf-stat">
        <div className="xf-cap"><span className="a">{x.capA}</span><span className="b">{x.capB}</span></div>
        <div className="xf-num"><small>{x.people}</small><strong>{people}{x.pu}</strong></div>
        <div className="xf-num"><small>{x.cost}</small><strong>−{save}%</strong></div>
        <div className="xf-num"><small>{x.hours}</small><strong>{hours}{x.hu}</strong></div>
      </div>
      <p className="why-note">{x.note}</p>
    </div>
  );
}

// One student's path, step by step, with times. An example, labelled as one.
function EduJourney({ j }) {
  const ref = useRef(null);
  const seen = useInView(ref, 0.3);
  return (
    <div ref={ref} className={'ej' + (seen ? ' on' : '')}>
      <span className="ef-ex light">{j.note}</span>
      <ol className="ej-list">
        {j.steps.map((s, i) => (
          <li key={i} style={{ transitionDelay: `${i * 0.35}s` }}>
            <span className="ej-dot"><i className="ic">{IC[s.i]}</i></span>
            <small>{s.d}</small>
            <b>{s.t}</b>
          </li>
        ))}
      </ol>
    </div>
  );
}

function ProductEduFunnel({ t, onNav }) {
  const p = t.products.edu;
  const ipf = t.products.ipf;
  return (
    <div className="ipf-page edu-page">
      <section className="section ipf-hero">
        <div className="wrap ipf-hero-grid">
          <div>
            <div className="kicker" style={{ marginBottom: 28 }}><Dot /> {p.kicker}</div>
            <h1 className="h-display ipf-title">{p.title1}<br /><span style={{ color: 'var(--accent)' }}>{p.title2}</span></h1>
            <p className="lede" style={{ marginTop: 24 }}>{p.lede}</p>
            <div className="edu-ind">{p.ind.map((x) => <span key={x}>{x}</span>)}</div>
            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginTop: 28 }}>
              <button className="btn btn-accent" onClick={() => onNav('contact')}>{p.cta1} <Arrow /></button>
              <a className="btn btn-ghost" href="#edu-stages" onClick={(e) => { e.preventDefault(); scrollToId('edu-stages'); }}>{p.cta2} <Arrow /></a>
            </div>
          </div>
          <EduFunnel key={p.kicker} h={p.hero} />
        </div>
      </section>

      <Block eyebrow={p.limit.eyebrow} title={p.limit.title} body={p.limit.body} tight><Bottleneck l={p.limit} /></Block>
      <Block eyebrow={p.clone.eyebrow} title={p.clone.title} body={p.clone.body} tight><EduClone c={p.clone} /></Block>
      <div id="edu-stages"><Block eyebrow={p.stages.eyebrow} title={p.stages.title} tight><EduStages s={p.stages} /></Block></div>
      <section className="section section-tight">
        <div className="wrap"><EduXform x={p.xform} /></div>
      </section>
      <Block eyebrow={p.journey.eyebrow} title={p.journey.title} tight><EduJourney j={p.journey} /></Block>
      <Block eyebrow={ipf.caseB.eyebrow} title={ipf.caseB.title} tight><CaseBars c={ipf.caseB} /></Block>
      <Block eyebrow={p.phases.eyebrow} title={p.phases.title} tight>
        <div className="process method-steps ipf-phases">
          {p.phases.list.map((s, i) => (
            <div key={i} className="step">
              <div className="step-num">/{s.n} · {s.w}</div>
              <div className="step-title">{s.t}</div>
              <div className="step-body">{s.b}</div>
            </div>
          ))}
        </div>
      </Block>
      <CTAStrip t={t} onNav={onNav} />
    </div>
  );
}

Object.assign(window, { ProductEduFunnel });
