const { useState: useStateT, useEffect: useEffectT, useRef: useRefT, useMemo: useMemoT } = React;

/* ---------------- NAV ---------------- */
function Nav() {
  useAutoHideNav();
  return (
    <nav id="site-nav" className="site-nav fixed top-0 left-0 right-0 z-50 border-b border-white/5 backdrop-blur-xl"
         style={{ background: 'rgba(5,7,11,0.6)' }}>
      <div className="max-w-7xl mx-auto px-6 md:px-8 h-16 flex items-center justify-between">
        <a href="#" className="flex items-center gap-2 group">
          <span className="text-[17px] font-semibold tracking-tightish">
            Leal<span className="relative inline-block">
              <span>ı</span>
              <span className="absolute rounded-full" style={{ top: '5px', left: '50%', transform: 'translateX(-50%)', width: '4px', height: '4px', background: '#5EEAD4', boxShadow: '0 0 8px rgba(94,234,212,0.8)' }}></span>
            </span>ntake
          </span>
        </a>
        <div className="hidden md:flex items-center gap-8 text-[13.5px] text-muted">
          {CONTENT.nav.map(n => (
            <a key={n.href} href={n.href} className="hover:text-ink transition-colors">{n.label}</a>
          ))}
        </div>
        <div className="flex items-center gap-3">
          <a href="#final-cta" className="hidden sm:inline-flex items-center gap-2 btn-primary rounded-full px-4 py-2 text-[13.5px]">
            Book demo <Icon.Arrow size={14} />
          </a>
        </div>
      </div>
    </nav>
  );
}

/* ---------------- TRANSCRIPT (live-typing) ---------------- */
function LiveTranscript() {
  const reduced = useReducedMotion();
  const scenarios = CONTENT.transcripts;
  const [idx, setIdx] = useStateT(0);
  const [rendered, setRendered] = useStateT([]);   // array of {t, who, lang, text, done}
  const [qualified, setQualified] = useStateT(false);

  useEffectT(() => {
    let cancelled = false;
    setRendered([]);
    setQualified(false);

    const scen = scenarios[idx];
    const run = async () => {
      for (let i = 0; i < scen.lines.length; i++) {
        if (cancelled) return;
        const line = scen.lines[i];
        // push line shell
        setRendered(r => [...r, { ...line, typed: '' }]);
        if (reduced) {
          setRendered(r => r.map((l, j) => j === i ? { ...l, typed: line.text } : l));
          await wait(500);
        } else {
          const chars = [...line.text];
          for (let c = 0; c < chars.length; c++) {
            if (cancelled) return;
            await wait(18 + Math.random() * 22);
            setRendered(r => r.map((l, j) => j === i ? { ...l, typed: line.text.slice(0, c + 1) } : l));
          }
          await wait(350);
        }
      }
      if (cancelled) return;
      await wait(400);
      setQualified(true);
      await wait(reduced ? 2000 : 4200);
      if (cancelled) return;
      setIdx(v => (v + 1) % scenarios.length);
    };
    run();
    return () => { cancelled = true; };
    // eslint-disable-next-line
  }, [idx]);

  const scen = scenarios[idx];

  return (
    <div className="glass p-5 md:p-6 w-full max-w-[460px] text-[13.5px] shadow-2xl" aria-live="polite">
      {/* call header */}
      <div className="flex items-center justify-between pb-4 mb-4 border-b border-white/5">
        <div className="flex items-center gap-3">
          <span className="relative inline-flex h-8 w-8 items-center justify-center rounded-full" style={{ background: 'rgba(94,234,212,0.12)', color: '#5EEAD4' }}>
            <Icon.Phone size={15} />
            <span className="absolute inset-0 rounded-full animate-ping" style={{ boxShadow: '0 0 0 2px rgba(94,234,212,0.35)', animationDuration: '2.4s' }}></span>
          </span>
          <div>
            <div className="text-ink font-medium leading-tight">Inbound call</div>
            <div className="font-mono text-[11px] text-faint leading-tight">+1 (305) ·· connecting</div>
          </div>
        </div>
        <div className="font-mono text-[11px] text-muted">LIVE</div>
      </div>

      {/* lines */}
      <div className="space-y-3 font-mono text-[12.5px] min-h-[168px]">
        {rendered.map((l, i) => (
          <div key={i} className="flex gap-3">
            <span className="text-faint shrink-0 w-12">[{l.t}]</span>
            <span className="shrink-0 w-[78px]" style={{ color: l.who === 'Caller' ? '#8B96A8' : '#5EEAD4' }}>
              {l.who}:
            </span>
            <span className="text-ink/90">
              {l.typed}
              {i === rendered.length - 1 && !qualified && l.typed.length < l.text.length && <span className="caret" />}
              {l.lang === 'es' && <span className="ml-2 text-[10px] px-1.5 py-0.5 rounded-full align-middle" style={{ background: 'rgba(167,139,250,0.12)', color: '#A78BFA', border: '1px solid rgba(167,139,250,0.25)' }}>ES</span>}
              {l.lang === 'en' && l.who === 'LealIntake' && <span className="ml-2 text-[10px] px-1.5 py-0.5 rounded-full align-middle" style={{ background: 'rgba(94,234,212,0.10)', color: '#5EEAD4', border: '1px solid rgba(94,234,212,0.25)' }}>EN</span>}
            </span>
          </div>
        ))}
      </div>

      {/* Qualified bar */}
      <div className={`mt-5 pt-4 border-t border-white/5 transition-opacity duration-500 ${qualified ? 'opacity-100' : 'opacity-30'}`}>
        <div className="flex items-center gap-3 flex-wrap">
          <span className="inline-flex items-center gap-1.5 text-[12px] font-mono" style={{ color: '#5EEAD4' }}>
            <Icon.Check size={14} /> Qualified
          </span>
          <span className="text-faint font-mono text-[12px]">·</span>
          <span className="font-mono text-[12px] text-ink/80">{scen.caseType}</span>
          <span className="text-faint font-mono text-[12px]">·</span>
          <span className="font-mono text-[12px] text-muted">Routed to {scen.routedTo}</span>
          <span className="text-faint font-mono text-[12px]">·</span>
          <span className="font-mono text-[12px] text-muted">Synced to {scen.synced}</span>
        </div>
      </div>
    </div>
  );
}
function wait(ms) { return new Promise(r => setTimeout(r, ms)); }

/* ---------------- HERO ---------------- */
function Hero() {
  return (
    <section className="relative overflow-hidden pt-32 md:pt-36 pb-24 md:pb-32">
      {/* background */}
      <div className="absolute inset-0 hero-grid" aria-hidden="true"></div>
      <div className="absolute inset-0 overflow-hidden pointer-events-none" aria-hidden="true">
        <div className="aurora aurora-a"></div>
        <div className="aurora aurora-b"></div>
        <div className="aurora aurora-c"></div>
      </div>
      {/* fade base */}
      <div className="absolute inset-x-0 bottom-0 h-48 pointer-events-none" style={{ background: 'linear-gradient(to bottom, transparent, #05070B)' }}></div>

      <div className="relative max-w-7xl mx-auto px-6 md:px-8">
        <div className="grid lg:grid-cols-[1.1fr_1fr] gap-12 lg:gap-16 items-center">
          {/* Left */}
          <div className="reveal">
            <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full glass text-[11px] font-mono tracking-wider text-muted mb-6">
              <span className="h-1.5 w-1.5 rounded-full" style={{ background: '#5EEAD4', boxShadow: '0 0 8px #5EEAD4' }}></span>
              INTAKE INTELLIGENCE LAYER · EN / ES
            </div>
            <h1 className="h-display text-[48px] sm:text-[64px] lg:text-[78px] text-ink">
              {CONTENT.hero.headline1}<br/>
              <span className="text-muted">In English. </span>
              <span className="text-muted">In Spanish.</span><br/>
              <span style={{ color: '#5EEAD4' }}>At 2 AM.</span>
            </h1>
            <p className="mt-7 text-[17px] md:text-[18px] leading-relaxed text-muted max-w-[560px]">
              {CONTENT.hero.sub}
            </p>
            <div className="mt-9 flex flex-wrap items-center gap-3">
              <a href={CONTENT.hero.ctaPrimary.href} className="btn-primary inline-flex items-center gap-2 rounded-full px-5 py-3 text-[14px]">
                {CONTENT.hero.ctaPrimary.label} <Icon.Arrow size={15} />
              </a>
              <a href={CONTENT.hero.ctaSecondary.href} className="btn-ghost inline-flex items-center gap-2 rounded-full px-5 py-3 text-[14px]">
                {CONTENT.hero.ctaSecondary.label}
              </a>
            </div>

            <div className="mt-10 flex flex-wrap gap-x-5 gap-y-2 text-[11.5px] font-mono text-faint uppercase tracking-wider">
              {CONTENT.hero.trust.split(' · ').map((t, i) => (
                <span key={i} className="flex items-center gap-2">
                  <span className="h-1 w-1 rounded-full bg-faint"></span>{t}
                </span>
              ))}
            </div>
          </div>

          {/* Right — transcript card */}
          <div className="reveal relative flex justify-center lg:justify-end">
            <div className="absolute -inset-6 -z-10 blur-3xl opacity-60" style={{ background: 'radial-gradient(closest-side, rgba(94,234,212,0.25), transparent 70%)' }}></div>
            <LiveTranscript />
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- SCANNER DIVIDER ---------------- */
function Scanner() {
  return (
    <div className="max-w-7xl mx-auto px-6 md:px-8">
      <div className="scanner"></div>
    </div>
  );
}

/* ---------------- SECTION HEADER ---------------- */
function SectionHeader({ eyebrow, headline, align = 'left', id }) {
  return (
    <div id={id} className={`mb-14 ${align === 'center' ? 'text-center mx-auto max-w-3xl' : 'max-w-3xl'} reveal`}>
      <div className="eyebrow mb-4">{eyebrow}</div>
      <h2 className="h-display text-[34px] sm:text-[44px] lg:text-[52px] text-ink">{headline}</h2>
    </div>
  );
}

/* ---------------- REVENUE LEAK ---------------- */
function LeakSection() {
  const { eyebrow, headline, metrics, closing, calculator } = CONTENT.leak;
  const [calls, setCalls] = useStateT(180);        // monthly calls
  const [fee, setFee] = useStateT(5000);           // avg case value
  const [missRate, setMissRate] = useStateT(35);   // % unanswered
  const [conversion, setConversion] = useStateT(15); // % of missed that would have converted

  const monthlyLeak = useMemoT(() => {
    return Math.round((calls * (missRate / 100)) * (conversion / 100) * fee);
  }, [calls, fee, missRate, conversion]);
  const annual = monthlyLeak * 12;

  return (
    <section id="leak" className="relative py-24 md:py-32">
      <div className="max-w-7xl mx-auto px-6 md:px-8">
        <SectionHeader eyebrow={eyebrow} headline={headline} />

        {/* Metric tiles */}
        <div className="grid md:grid-cols-3 gap-5">
          {metrics.map((m, i) => (
            <div key={i} className="glass glass-hover p-8 reveal">
              <div className="h-display text-[56px] md:text-[64px] leading-none" style={{ color: '#F59E0B' }}>
                {m.custom
                  ? <span>{m.custom}</span>
                  : <CountUp target={m.value} prefix={m.prefix || ''} suffix={m.suffix || ''} />
                }
                {m.unit && <span className="text-[18px] font-sans text-muted font-normal ml-2">{m.unit}</span>}
              </div>
              <p className="mt-5 text-[15px] leading-relaxed text-muted">{m.label}</p>
            </div>
          ))}
        </div>

        <p className="mt-14 h-display text-[28px] sm:text-[34px] lg:text-[40px] max-w-4xl reveal">
          {"That's "}<span style={{ color: '#F59E0B' }}>$600K a year</span>{' walking out the door. '}
          <span className="text-muted">Our system costs less than 5% of it.</span>
        </p>

        {/* Calculator */}
        <div className="mt-16 glass p-7 md:p-10 reveal">
          <div className="grid md:grid-cols-[1fr_1px_1fr] gap-10 items-start">
            <div>
              <div className="eyebrow mb-2">LEAK CALCULATOR</div>
              <h3 className="h-display text-[26px] md:text-[30px]">{calculator.title}</h3>
              <p className="mt-2 text-muted text-[14.5px]">{calculator.subtitle}</p>

              <div className="mt-8 space-y-6">
                <Slider label="Monthly intake calls" value={calls} setValue={setCalls}
                  min={30} max={600} step={10}
                  display={`${calls} calls / mo`} />
                <Slider label="Average case value" value={fee} setValue={setFee}
                  min={1500} max={15000} step={250}
                  display={`$${fee.toLocaleString()}`} />
                <Slider label="Unanswered rate" value={missRate} setValue={setMissRate}
                  min={5} max={60} step={1}
                  display={`${missRate}%`} />
                <Slider label="Of those, would've retained" value={conversion} setValue={setConversion}
                  min={5} max={35} step={1}
                  display={`${conversion}%`} />
              </div>
            </div>

            <div className="hidden md:block w-px self-stretch" style={{ background: 'linear-gradient(to bottom, transparent, rgba(255,255,255,0.12), transparent)' }}></div>

            <div className="md:pl-2">
              <div className="font-mono text-[11px] tracking-wider text-faint uppercase">Your leak</div>
              <div className="mt-3 h-display leading-none text-[64px] md:text-[84px]" style={{ color: '#F59E0B' }}>
                ${monthlyLeak.toLocaleString()}
              </div>
              <div className="mt-1 text-muted text-[14px]">per month — in cases that called and got nothing.</div>

              <div className="mt-8 grid grid-cols-2 gap-3">
                <StatTile label="Annualized" value={`$${annual.toLocaleString()}`} />
                <StatTile label="LealIntake cost (yr 1)" value="$25,000" sub="less than 5%" good />
              </div>

              <div className="mt-6 text-[13px] font-mono text-faint">
                Math: calls × unanswered × would-retain × case value.
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Slider({ label, value, setValue, min, max, step, display }) {
  return (
    <div>
      <div className="flex items-baseline justify-between mb-2">
        <label className="text-[13.5px] text-muted">{label}</label>
        <span className="font-mono text-[13px] text-ink">{display}</span>
      </div>
      <input type="range" min={min} max={max} step={step} value={value}
             onChange={(e) => setValue(Number(e.target.value))} />
    </div>
  );
}

function StatTile({ label, value, sub, good }) {
  return (
    <div className="rounded-xl border border-white/5 p-4" style={{ background: 'rgba(255,255,255,0.02)' }}>
      <div className="font-mono text-[10.5px] uppercase tracking-wider text-faint">{label}</div>
      <div className="mt-1 h-display text-[22px]" style={{ color: good ? '#5EEAD4' : '#E6EDF7' }}>{value}</div>
      {sub && <div className="text-[12px] text-muted mt-0.5">{sub}</div>}
    </div>
  );
}

Object.assign(window, { Nav, Hero, Scanner, SectionHeader, LeakSection, LiveTranscript });
