/* ============================================================
   Gaung AI — Shared Components
   ============================================================ */

const { useState, useEffect, useLayoutEffect, useMemo, useRef } = React;

// ---- Language context ------------------------------------
const LangCtx = React.createContext({ lang: 'id', setLang: () => {} });

function t(entry, lang) {
  if (!entry) return '';
  if (typeof entry === 'string') return entry;
  return entry[lang] || entry.id || '';
}

// ---- Logo ------------------------------------------------
function Logo() {
  return (
    <a href="#home" className="logo" aria-label="Gaung.ai" style={{display:'flex',alignItems:'center'}}>
      <img src="assets/logo-wordmark.png" alt="Gaung.ai" style={{height:32,width:'auto',objectFit:'contain'}}/>
    </a>
  );
}

// ---- Nav -------------------------------------------------
function Nav({ route, setRoute }) {
  const { lang, setLang } = React.useContext(LangCtx);
  const C = window.GAUNG_CONTENT.nav;
  // When the user is on a wizard result page (route = "r/<sessionId>"), carry
  // the wizard session into the signup link so the dashboard prefills their
  // Brand DNA + campaigns instead of asking for the URL again.
  const wizardId = route && route.startsWith('r/') ? route.slice(2) : '';
  const signupHref = wizardId
    ? `https://dashboard.gaung.app/signup?wizard=${wizardId}`
    : 'https://dashboard.gaung.app/signup';
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 6);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const links = [
    ['home', C.home],
    ['services', C.services],
    ['cases', C.cases],
    ['pricing', C.pricing],
  ];

  useEffect(() => { setMobileOpen(false); }, [route]);

  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="nav-inner">
        <Logo />
        <div className="nav-links">
          {links.map(([k, entry]) => (
            <a
              key={k}
              href={`#${k}`}
              className={`nav-link ${route === k ? 'active' : ''}`}
              onClick={(e) => { e.preventDefault(); setRoute(k); }}
            >
              {t(entry, lang)}
            </a>
          ))}
        </div>
        <div className="nav-right">
          <div className="lang-toggle" role="group" aria-label="Language">
            <button className={lang === 'id' ? 'active' : ''} onClick={() => setLang('id')}>ID</button>
            <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
          </div>
          <a href="https://dashboard.gaung.app" className="nav-link nav-login-desktop" style={{padding:'8px 14px'}}>
            {t(C.login, lang)}
          </a>
          <a href={signupHref} className="btn btn-primary nav-cta-desktop">
            {t(C.demo, lang)}
          </a>
          <button
            className="nav-hamburger"
            aria-label="Menu"
            aria-expanded={mobileOpen}
            onClick={() => setMobileOpen(o => !o)}
          >
            <span/><span/><span/>
          </button>
        </div>
      </div>
      {mobileOpen && (
        <div className="nav-mobile-drawer">
          {links.map(([k, entry]) => (
            <a
              key={k}
              href={`#${k}`}
              className={`nav-mobile-link ${route === k ? 'active' : ''}`}
              onClick={(e) => { e.preventDefault(); setRoute(k); }}
            >
              {t(entry, lang)}
            </a>
          ))}
          <div className="nav-mobile-divider"/>
          <a href="https://dashboard.gaung.app" className="nav-mobile-link">{t(C.login, lang)}</a>
          <a href={signupHref} className="btn btn-primary" style={{marginTop:8,textAlign:'center'}}>
            {t(C.demo, lang)}
          </a>
        </div>
      )}
    </nav>
  );
}

// ---- Footer ----------------------------------------------
function Footer({ setRoute }) {
  const { lang } = React.useContext(LangCtx);
  const F = window.GAUNG_CONTENT.footer;
  const N = window.GAUNG_CONTENT.nav;

  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-cols">
          <div>
            <div style={{marginBottom:14}}>
              <img src="assets/logo-wordmark.png" alt="Gaung.ai" style={{height:32,width:'auto',objectFit:'contain',filter:'brightness(0) invert(1)'}}/>
            </div>
            <p style={{fontSize:14,color:'oklch(70% 0.008 70)',maxWidth:280,lineHeight:1.5}}>{t(F.tag, lang)}</p>
            <p style={{fontSize:13,color:'oklch(55% 0.008 70)',marginTop:24}}>halo@gaung.app</p>
            <p style={{fontSize:13,color:'oklch(70% 0.008 70)',marginTop:16,fontWeight:600}}>PT Gaung Elevasi Digital</p>
            <p style={{fontSize:12.5,color:'oklch(55% 0.008 70)',marginTop:4,lineHeight:1.5}}>Tangerang Selatan, Banten, Indonesia</p>
          </div>
          <div>
            <h5>{t(F.product, lang)}</h5>
            <ul>
              <li><a href="#services" onClick={(e)=>{e.preventDefault();setRoute('services')}}>{t(N.services, lang)}</a></li>
              <li><a href="#pricing" onClick={(e)=>{e.preventDefault();setRoute('pricing')}}>{t(N.pricing, lang)}</a></li>
            </ul>
          </div>
          <div>
            <h5>{t(F.company, lang)}</h5>
            <ul>
              <li><a href="#cases" onClick={(e)=>{e.preventDefault();setRoute('cases')}}>{t(N.cases, lang)}</a></li>
              <li><a href="#contact" onClick={(e)=>{e.preventDefault();setRoute('contact')}}>{t(N.contact, lang)}</a></li>
              <li><a href={`mailto:halo@gaung.app?subject=${encodeURIComponent(t({id:'Lamaran kerja — Gaung.ai',en:'Career inquiry — Gaung.ai'}, lang))}`}>{t({id:'Karir',en:'Careers'}, lang)}</a></li>
            </ul>
          </div>
          <div>
            <h5>{t(F.resources, lang)}</h5>
            <ul>
              <li><a href="#blog" onClick={(e)=>{e.preventDefault();setRoute('blog')}}>{t(N.blog, lang)}</a></li>
            </ul>
          </div>
          <div>
            <h5>{t(F.legal, lang)}</h5>
            <ul>
              <li><a href="/privacy">{t({id:'Kebijakan Privasi',en:'Privacy Policy'}, lang)}</a></li>
              <li><a href="/terms">{t({id:'Syarat Layanan',en:'Terms of Service'}, lang)}</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <div>{t(F.rights, lang)}</div>
          <a href="https://dashboard.gaung.app" style={{color:'inherit',borderBottom:'1px solid currentColor',paddingBottom:1}}>dashboard.gaung.app ↗</a>
        </div>
      </div>
    </footer>
  );
}

// ---- Placeholder image -----------------------------------
function Placeholder({ label, ratio = '4 / 3', style }) {
  return (
    <div className="placeholder" style={{aspectRatio: ratio, ...style}}>
      <span>{label}</span>
    </div>
  );
}

// ---- Hero (with variants) --------------------------------
function Hero({ variant, setRoute }) {
  const { lang } = React.useContext(LangCtx);
  const H = window.GAUNG_CONTENT.home;

  const headlines = {
    A: (
      <h1 className="h-display reveal">
        {t(H.heroA1, lang)}<br/>
        <span className="grad">{t(H.heroA2, lang)}</span>{' '}
        <span className="serif">{t(H.heroA3, lang)}</span>
      </h1>
    ),
    B: (
      <h1 className="h-display reveal">
        {t(H.heroB1, lang)}<br/>
        <span className="serif">{t(H.heroB2, lang)}</span>{' '}
        {t(H.heroB3, lang)}
      </h1>
    ),
    C: (
      <h1 className="h-display reveal">
        <span className="serif">{t(H.heroC1, lang)}</span>{' '}
        {t(H.heroC2, lang)}<br/>
        <span className="grad">{t(H.heroC3, lang)}</span>
      </h1>
    ),
  };

  return (
    <section className="hero" style={{minHeight:'100svh', display:'flex', alignItems:'center', paddingBlock:'clamp(80px,10vw,120px)'}}>
      <div className="wrap" style={{width:'100%'}}>
        <div style={{maxWidth:720}}>
          <div className="hero-badge reveal">
            <span className="hero-badge-pill">{t({id:'BARU',en:'NEW'}, lang)}</span>
            <span>{t(H.badge, lang)}</span>
          </div>
          <div>
            {headlines[variant] || headlines.A}
          </div>
          <p className="lead mt-6 reveal reveal-1">{t(H.heroSub, lang)}</p>
          <div className="reveal reveal-2" style={{marginTop:36}}>
            <WizardInput setRoute={setRoute} autoFocus={true}/>
          </div>
          <div className="hero-sub-row reveal reveal-3">
            <span>
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><circle cx="7" cy="7" r="6" stroke="#ea008c" strokeWidth="1.2"/><path d="M4 7l2 2 4-4" stroke="#ea008c" strokeWidth="1.4" fill="none"/></svg>
              {t(H.subHero1, lang)}
            </span>
            <span>
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><circle cx="7" cy="7" r="6" stroke="#ea008c" strokeWidth="1.2"/><path d="M4 7l2 2 4-4" stroke="#ea008c" strokeWidth="1.4" fill="none"/></svg>
              {t(H.subHero2, lang)}
            </span>
            <span>
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><circle cx="7" cy="7" r="6" stroke="#ea008c" strokeWidth="1.2"/><path d="M4 7l2 2 4-4" stroke="#ea008c" strokeWidth="1.4" fill="none"/></svg>
              {t(H.subHero3, lang)}
            </span>
          </div>
        </div>

        <div className="reveal reveal-4" style={{marginTop:72}}>
          <HeroDashMock />
        </div>
      </div>
    </section>
  );
}

// ---- Wizard input (paste URL → AI generates ICP + 3 campaigns) ----
const ORCH_URL = window.GAUNG_ORCH_URL || 'https://orchestrator.gaung.app';

// 2026-06-08 Multi-Input Wizard CR (v2 redesign — single smart input).
// Satu field, satu tombol kirim, satu icon klip kertas untuk upload Compro.
// PRD US-1.1: backend menolak URL marketplace/sosmed dengan pesan ramah.
// File upload mengambil alih input field jadi chip ber-ikon yang bisa di-clear.
const MAX_UPLOAD_MB = 10;
const ALLOWED_EXTS = ['pdf', 'docx', 'md', 'txt'];

// Client-side URL classifier (mirrors backend classifyUnsupportedUrl).
// Catches Shopee/Instagram/Tokopedia before any API call — faster feedback,
// no network round-trip needed.
const _MARKETPLACE_HOSTS = [
  'tokopedia.com','shopee.co.id','shopee.com','bukalapak.com','lazada.co.id','blibli.com',
];
const _SOCIAL_HOSTS = [
  'instagram.com','tiktok.com','facebook.com','fb.com','twitter.com','x.com',
  'linkedin.com','youtube.com','youtu.be','threads.net','t.me','wa.me','linktr.ee','lynk.id',
];
function classifyUrlClient(rawUrl) {
  let host;
  try { host = new URL(rawUrl.startsWith('http') ? rawUrl : `https://${rawUrl}`).hostname.toLowerCase().replace(/^www\./, ''); }
  catch { return null; }
  const matches = (list) => list.some(h => host === h || host.endsWith('.' + h));
  if (matches(_MARKETPLACE_HOSTS)) return 'Halaman toko online tidak memiliki cukup informasi bisnis untuk kami analisa. Coba masukkan website perusahaan kamu, atau upload PDF company profile.';
  if (matches(_SOCIAL_HOSTS)) return 'Profil media sosial tidak cukup untuk analisa mendalam. Coba masukkan website bisnis kamu, atau upload PDF company profile.';
  return null;
}

function WizardInput({ setRoute, autoFocus = false }) {
  const { lang } = React.useContext(LangCtx);
  const [url, setUrl] = useState('');
  const [file, setFile] = useState(null);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState(null);
  const fileInputRef = React.useRef(null);

  async function submitUrl() {
    if (!isValidUrl(url)) {
      setError(t({id:'URL tidak valid. Contoh: https://websitebisnis.com', en:'Invalid URL. Example: https://yourbusiness.com'}, lang));
      return;
    }
    const unsupportedMsg = classifyUrlClient(url);
    if (unsupportedMsg) {
      setError(unsupportedMsg);
      return;
    }
    setSubmitting(true);
    try {
      const res = await fetch(`${ORCH_URL}/v1/public/wizard`, {
        method: 'POST',
        headers: {'content-type':'application/json'},
        body: JSON.stringify({ url: normalize(url) }),
      });
      await handleResponse(res);
    } catch (e) {
      setError(e.message);
      setSubmitting(false);
    }
  }

  async function submitFile() {
    const ext = (file.name.split('.').pop() || '').toLowerCase();
    if (!ALLOWED_EXTS.includes(ext)) {
      setError(t({id:'Format harus PDF, DOCX, MD, atau TXT.', en:'Format must be PDF, DOCX, MD, or TXT.'}, lang));
      return;
    }
    if (file.size > MAX_UPLOAD_MB * 1024 * 1024) {
      setError(t({id:`File terlalu besar. Maksimum ${MAX_UPLOAD_MB}MB.`, en:`File too large. Max ${MAX_UPLOAD_MB}MB.`}, lang));
      return;
    }
    if (file.size === 0) {
      setError(t({id:'File kosong. Coba pilih ulang.', en:'Empty file. Try again.'}, lang));
      return;
    }
    setSubmitting(true);
    try {
      const fd = new FormData();
      fd.append('file', file);
      const res = await fetch(`${ORCH_URL}/v1/public/wizard/upload`, {
        method: 'POST',
        body: fd,
      });
      await handleResponse(res);
    } catch (e) {
      setError(e.message);
      setSubmitting(false);
    }
  }

  async function handleResponse(res) {
    if (!res.ok) {
      if (res.status === 429) {
        setError(t({id:'Terlalu banyak percobaan dari IP ini. Coba lagi besok.', en:'Too many requests from this IP. Try tomorrow.'}, lang));
      } else if (res.status === 413) {
        setError(t({id:`File terlalu besar. Maksimum ${MAX_UPLOAD_MB}MB.`, en:`File too large. Max ${MAX_UPLOAD_MB}MB.`}, lang));
      } else {
        let msg = '';
        try {
          const body = await res.json();
          msg = body.message || body.error || '';
        } catch { /* not json */ }
        setError(msg || `${res.status}`);
      }
      setSubmitting(false);
      return;
    }
    const body = await res.json();
    window.location.hash = `r/${body.session_id}`;
    setRoute(`r/${body.session_id}`);
  }

  function submit() {
    setError(null);
    if (file) submitFile();
    else submitUrl();
  }

  function onFilePick(e) {
    const picked = e.target.files?.[0] || null;
    setFile(picked);
    setUrl('');
    setError(null);
  }

  function clearFile() {
    setFile(null);
    if (fileInputRef.current) fileInputRef.current.value = '';
  }

  const hasFile = !!file;
  const btnDisabled = submitting || (!hasFile && !url.trim());
  const buttonLabel = submitting
    ? t({id:'Menganalisis…', en:'Analyzing…'}, lang)
    : hasFile
    ? t({id:'Analisa Compro saya', en:'Analyze my Compro'}, lang)
    : t({id:'Bedah strategi saya', en:'Generate my strategy'}, lang);

  return (
    <div className="wizard-input">
      <div className="wizard-shell" data-has-file={hasFile ? 'true' : 'false'}>
        {hasFile ? (
          <div className="wizard-chip" title={file.name}>
            <span className="wizard-chip-icon" aria-hidden>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                <polyline points="14 2 14 8 20 8"/>
              </svg>
            </span>
            <span className="wizard-chip-name">{file.name}</span>
            <span className="wizard-chip-size">{(file.size/1024).toFixed(0)} KB</span>
            <button
              type="button"
              onClick={clearFile}
              disabled={submitting}
              aria-label={t({id:'Hapus file', en:'Remove file'}, lang)}
              className="wizard-chip-x"
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M18 6L6 18M6 6l12 12"/>
              </svg>
            </button>
          </div>
        ) : (
          <input
            type="url"
            value={url}
            onChange={(e)=>setUrl(e.target.value)}
            onKeyDown={(e)=>{if(e.key==='Enter')submit();}}
            placeholder="https://websitebisnis.com"
            disabled={submitting}
            autoFocus={autoFocus}
            spellCheck={false}
            className="wizard-input-field"
          />
        )}

        <input
          ref={fileInputRef}
          type="file"
          accept=".pdf,.docx,.md,.txt"
          onChange={onFilePick}
          disabled={submitting}
          style={{display:'none'}}
        />
        {!hasFile && (
          <button
            type="button"
            onClick={() => fileInputRef.current?.click()}
            disabled={submitting}
            aria-label={t({id:'Upload Company Profile', en:'Upload Company Profile'}, lang)}
            title={t({id:'Atau upload Compro (PDF/DOCX/MD/TXT)', en:'Or upload Compro (PDF/DOCX/MD/TXT)'}, lang)}
            className="wizard-clip"
          >
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 17.93 8.8l-8.57 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/>
            </svg>
          </button>
        )}

        <button
          onClick={submit}
          disabled={btnDisabled}
          className="btn btn-grad wizard-input-btn"
        >
          {buttonLabel} {!submitting && <span aria-hidden>→</span>}
        </button>
      </div>

      {error && <div className="wizard-input-error">{error}</div>}
      <div className="wizard-input-help">
        {t({
          id: 'Masukkan URL website bisnis · atau klik 📎 untuk upload Company Profile (PDF/DOCX). Gratis, tanpa daftar, hasil ~30 detik.',
          en: 'Enter your business website URL · or click 📎 to upload a Company Profile (PDF/DOCX). Free, no signup, results in ~30 seconds.'
        }, lang)}
      </div>
    </div>
  );
}

function isValidUrl(s) {
  try {
    const u = new URL(s.startsWith('http') ? s : `https://${s}`);
    return u.protocol === 'http:' || u.protocol === 'https:';
  } catch { return false; }
}

function normalize(s) {
  return s.startsWith('http') ? s : `https://${s}`;
}

// ---- Wizard result page (polls orchestrator until ICP + campaigns ready) ----
const TERMINAL_STATUSES = new Set(['ready', 'error']);

function WizardResultPage({ sessionId, setRoute }) {
  const { lang } = React.useContext(LangCtx);
  const [session, setSession] = useState(null);
  const [error, setError] = useState(null);

  // Audio lives here so it starts immediately on mount — user gesture (the click
  // that triggered navigation) is still valid. By the time results load (20-40 s),
  // gesture context has expired and play() would be blocked.
  const audioRef = useRef(null);
  const [soundPlaying, setSoundPlaying] = useState(false);

  useEffect(() => {
    const a = audioRef.current;
    if (!a) return;
    a.volume = 0.35;
    const tryPlay = () => {
      a.play().then(() => setSoundPlaying(true)).catch(() => setSoundPlaying(false));
    };
    tryPlay();
    const onFirstClick = () => { if (a.paused) tryPlay(); };
    window.addEventListener('click', onFirstClick, { once: true });
    return () => {
      window.removeEventListener('click', onFirstClick);
      a.pause();
    };
  }, []);

  function toggleSound() {
    const a = audioRef.current;
    if (!a) return;
    if (a.paused) {
      a.play().then(() => setSoundPlaying(true)).catch(() => setSoundPlaying(false));
    } else {
      a.pause();
      setSoundPlaying(false);
    }
  }

  useEffect(() => {
    let stopped = false;
    async function poll() {
      try {
        const res = await fetch(`${ORCH_URL}/v1/public/wizard/${sessionId}`);
        if (!res.ok) {
          setError(`${res.status}`);
          return;
        }
        const body = await res.json();
        if (stopped) return;
        setSession(body.session);
        // M63 — keep polling until leads hunt also completes, even after
        // wizard.status === 'ready'. Leads run in parallel and finish a bit
        // later (~120s vs ~90s for DNA + campaigns).
        const wizardDone = TERMINAL_STATUSES.has(body.session.status);
        const leadsStatus = body.session.preview_leads?.status;
        const leadsTerminal = !leadsStatus || ['ready','cached','budget_exhausted','disabled','failed'].includes(leadsStatus);
        if (!wizardDone || !leadsTerminal) {
          setTimeout(poll, 1500);
        }
      } catch (e) {
        if (!stopped) setError(e.message);
      }
    }
    poll();
    return () => { stopped = true; };
  }, [sessionId]);

  // Always-mounted audio element — must stay outside conditional renders.
  const audioEl = (
    <audio ref={audioRef} loop preload="auto" style={{display:'none'}}>
      <source src="https://upload.wikimedia.org/wikipedia/commons/c/c7/Mozart_-_The_Marriage_of_Figaro_-_K_492_-_Overture.ogg" type="audio/ogg"/>
      <source src="https://upload.wikimedia.org/wikipedia/commons/transcoded/c/c7/Mozart_-_The_Marriage_of_Figaro_-_K_492_-_Overture.ogg/Mozart_-_The_Marriage_of_Figaro_-_K_492_-_Overture.ogg.mp3" type="audio/mpeg"/>
    </audio>
  );

  if (error) {
    return (
      <>
        {audioEl}
        <section className="section">
          <div className="wrap" style={{textAlign:'center', paddingBlock:80}}>
            <h2 className="h-section">{t({id:'Sesi tidak ditemukan', en:'Session not found'}, lang)}</h2>
            <p className="lead mt-4">{error}</p>
            <a href="#home" className="btn btn-grad mt-6" onClick={(e)=>{e.preventDefault();setRoute('home');}} style={{display:'inline-block', marginTop:24}}>
              {t({id:'← Mulai analisis baru', en:'← Start new analysis'}, lang)}
            </a>
          </div>
        </section>
        <WizardSoundtrack playing={soundPlaying} onToggle={toggleSound} lang={lang}/>
      </>
    );
  }
  if (!session) {
    return (
      <>
        {audioEl}
        <WizardLoading url=""/>
        <WizardSoundtrack playing={soundPlaying} onToggle={toggleSound} lang={lang}/>
      </>
    );
  }
  if (!TERMINAL_STATUSES.has(session.status)) {
    return (
      <>
        {audioEl}
        <WizardLoading url={session.url} status={session.status}/>
        <WizardSoundtrack playing={soundPlaying} onToggle={toggleSound} lang={lang}/>
      </>
    );
  }
  if (session.status === 'error') {
    return (
      <>
        {audioEl}
        <section className="section">
          <div className="wrap" style={{textAlign:'center', paddingBlock:80}}>
            <h2 className="h-section">{t({id:'Analisis gagal', en:'Analysis failed'}, lang)}</h2>
            <p className="lead mt-4">{session.error || t({id:'Coba URL lain.', en:'Try a different URL.'}, lang)}</p>
            <a href="#home" className="btn btn-grad" onClick={(e)=>{e.preventDefault();setRoute('home');}} style={{display:'inline-block', marginTop:24}}>
              {t({id:'← Coba URL lain', en:'← Try a different URL'}, lang)}
            </a>
          </div>
        </section>
        <WizardSoundtrack playing={soundPlaying} onToggle={toggleSound} lang={lang}/>
      </>
    );
  }

  const icp = session.icp || {};
  const campaigns = (session.campaigns && session.campaigns.campaigns) || [];
  const mi = getMarketInsights(icp);
  const hostname = (() => { try { return new URL(session.url).hostname; } catch(e) { return session.url; } })();

  // Signup is its own page on the dashboard (dashboard.gaung.app/signup). We
  // pass ?wizard=<sessionId> so it prefills Brand DNA + campaigns and shows the
  // "Cek email" confirmation on a clean dedicated page, instead of inlining the
  // form (and its done-state) here on the analysis result page. sessionId comes
  // from THIS active result page, so no stale wizard id can leak from old tabs.
  const signupUrl = `https://dashboard.gaung.app/signup?${icp.recommended_plan ? `plan=${icp.recommended_plan}&` : ''}wizard=${sessionId}`;

  return (
    <>
      {audioEl}
      <section className="section" style={{paddingTop:60}}>
        <div className="wrap">

          {/* Page header */}
          <div style={{textAlign:'center', marginBottom:40}}>
            <div className="hero-badge" style={{justifyContent:'center'}}>
              <span className="hero-badge-pill">AI</span>
              <span>{t({id:'Hasil Analisis Gaung', en:'Gaung Analysis'}, lang)}</span>
            </div>
            <h1 className="h-display" style={{marginTop:24}}>
              {t({id:'Strategi sales buat', en:'Sales strategy for'}, lang)}{' '}
              <span className="grad">{icp.business_name || hostname}</span>
            </h1>
            <p className="lead mt-4" style={{maxWidth:520, margin:'16px auto 0'}}>
              {t({id:'AI Gaung sudah baca website kamu. Berikut Business DNA + ICP + 3 strategi kampanye siap diaktifkan.', en:'Gaung AI has read your site. Here is your Business DNA + ICP + 3 campaign strategies, ready to activate.'}, lang)}
            </p>
          </div>

          {/* PRD Epic 1 (US-1.1): public wizard output = Business DNA + ICP only.
              Market-analysis metrics panel removed (no "lead potential / market
              size" at this stage). */}

          {/* Business DNA card */}
          <div style={{marginBottom:48, border:'1px solid var(--dark-line)', borderRadius:16, overflow:'hidden'}}>

            {/* Card header strip */}
            <div style={{
              background:'linear-gradient(135deg, oklch(18% 0.025 310) 0%, oklch(15% 0.02 340) 100%)',
              padding:'18px 28px', display:'flex', alignItems:'center', justifyContent:'space-between'
            }}>
              <div>
                <div style={{fontSize:10, color:'var(--gm)', fontWeight:700, letterSpacing:'.1em', textTransform:'uppercase', marginBottom:4}}>
                  Business DNA
                </div>
                <div style={{fontSize:12, color:'oklch(60% 0.008 70)'}}>
                  {t({id:'Diekstrak otomatis dari website kamu', en:'Auto-extracted from your website'}, lang)}
                </div>
              </div>
              <div style={{
                background:'var(--grad)', padding:'5px 14px', borderRadius:99,
                fontSize:10, fontWeight:700, color:'#fff', letterSpacing:'.07em'
              }}>AI VERIFIED</div>
            </div>

            {/* Business summary */}
            {icp.business_summary && (
              <div style={{padding:'20px 28px', borderBottom:'1px solid var(--border)', background:'#fff'}}>
                <p style={{margin:0, fontSize:15, lineHeight:1.65, color:'var(--ink)'}}>{icp.business_summary}</p>
              </div>
            )}

            {/* DNA tag grid */}
            <div style={{padding:'20px 28px', background:'#fff'}}>
              <div className="dna-grid">
                {icp.industry && (
                  <div>
                    <div className="eyebrow" style={{marginBottom:8}}>{t({id:'Industri', en:'Industry'}, lang)}</div>
                    <span style={{
                      display:'inline-flex', alignItems:'center',
                      background:'oklch(97% 0.01 310)', border:'1px solid oklch(90% 0.02 310)',
                      borderRadius:8, padding:'6px 14px', fontSize:13, fontWeight:500, color:'oklch(35% 0.05 310)'
                    }}>{icp.industry}</span>
                  </div>
                )}
                {icp.target_market && icp.target_market.length > 0 && (
                  <div>
                    <div className="eyebrow" style={{marginBottom:8}}>{t({id:'Target Market', en:'Target Market'}, lang)}</div>
                    <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
                      {icp.target_market.slice(0,4).map((it,i) => (
                        <span key={i} style={{
                          background:'oklch(96% 0.015 240)', border:'1px solid oklch(88% 0.025 240)',
                          borderRadius:6, padding:'4px 10px', fontSize:12, color:'oklch(35% 0.06 240)'
                        }}>{it}</span>
                      ))}
                    </div>
                  </div>
                )}
                {icp.pain_points && icp.pain_points.length > 0 && (
                  <div>
                    <div className="eyebrow" style={{marginBottom:8}}>{t({id:'Pain Points', en:'Pain Points'}, lang)}</div>
                    <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
                      {icp.pain_points.slice(0,4).map((it,i) => (
                        <span key={i} style={{
                          background:'oklch(97% 0.01 20)', border:'1px solid oklch(88% 0.03 20)',
                          borderRadius:6, padding:'4px 10px', fontSize:12, color:'oklch(40% 0.08 20)'
                        }}>{it}</span>
                      ))}
                    </div>
                  </div>
                )}
                {icp.value_props && icp.value_props.length > 0 && (
                  <div>
                    <div className="eyebrow" style={{marginBottom:8}}>{t({id:'Value Props', en:'Value Props'}, lang)}</div>
                    <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
                      {icp.value_props.slice(0,4).map((it,i) => (
                        <span key={i} style={{
                          background:'oklch(96% 0.015 145)', border:'1px solid oklch(86% 0.04 145)',
                          borderRadius:6, padding:'4px 10px', fontSize:12, color:'oklch(35% 0.1 145)'
                        }}>{it}</span>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* ICP Persona quote */}
            {icp.example_customer_persona && (
              <div style={{padding:'0 28px 24px', background:'#fff'}}>
                <div style={{
                  background:'oklch(97.5% 0.008 300)', border:'1px solid oklch(90% 0.015 300)',
                  borderLeft:'3px solid var(--gm)', borderRadius:10, padding:'16px 20px'
                }}>
                  <div style={{fontSize:9, color:'var(--gm)', fontWeight:700, letterSpacing:'.1em', textTransform:'uppercase', marginBottom:8}}>
                    {t({id:'ICP Persona', en:'ICP Persona'}, lang)}
                  </div>
                  <p style={{margin:0, fontSize:13, fontStyle:'italic', lineHeight:1.65, color:'var(--ink)'}}>{icp.example_customer_persona}</p>
                </div>
              </div>
            )}
          </div>

          {/* PRD Epic 1 (US-1.1): lead preview removed from public wizard —
              output is Business DNA + ICP (+ the 3 strategy demos) only.
              Lead generation is shown after signup, not pre-signup. */}

          {/* Campaign strategies heading */}
          <div style={{marginBottom:24, marginTop:48, textAlign:'center'}}>
            <h2 className="h-section">{t({id:'3 strategi yang paling cocok', en:'3 best-fit strategies'}, lang)}</h2>
            <p className="lead mt-4" style={{maxWidth:480, margin:'16px auto 0'}}>
              {t({id:'Pilih satu — daftar + aktivasi engine dalam ~60 detik, langsung live.', en:'Pick one — sign up + activate in ~60 seconds, go live immediately.'}, lang)}
            </p>
          </div>
          <div className="campaign-grid">
            {campaigns.map((c) => (
              <CampaignCard
                key={c.id}
                campaign={c}
                selected={false}
                onSelect={() => {
                  // Picking a strategy = sign up to activate it. Go to the
                  // dedicated dashboard signup page (separate from this result
                  // page) carrying the wizard session for DNA prefill.
                  window.location.href = signupUrl;
                }}
              />
            ))}
          </div>

          {/* M62 — Email-me-this CTA. Lets prospect share with decision-maker
              before committing to signup. Sits between campaigns + signup form. */}
          <EmailResultCta sessionId={sessionId}/>

          {/* F-038 — WhatsApp share. Viral acquisition: prospect shares their
              own analysis result with peers via WA. wa.me/?text=... pattern —
              user picks recipient themselves, no third-party PII processed.
              UTM only at campaign level (no recipient tracking) for UU PDP. */}
          <WhatsAppShareCta
            businessName={icp.business_name || hostname}
            leadsCount={mi.leads}
            industry={icp.industry || ''}
          />

          {/* F-022 — AI plan recommendation card. LLM picks free/starter/business
              based on ICP signals; plan_reasoning explains why. Guard against
              missing/invalid values (LLM may omit). */}
          <PlanRecommendationCard
            plan={icp.recommended_plan}
            reasoning={icp.plan_reasoning}
            lang={lang}
            sessionId={sessionId}
          />
        </div>
      </section>
      <WizardSoundtrack playing={soundPlaying} onToggle={toggleSound} lang={lang}/>
    </>
  );
}

/**
 * Phase-driven loading. Reads `status` from the session row and maps it
 * to one of four pipeline stages. Each stage has its own microcopy +
 * detailed substep so the user sees what the AI is actually doing,
 * not a fake timer.
 *
 * Phase rotation also runs independently so the substep label cycles
 * every 2s while the backend is on the same phase — gives the
 * impression of continuous work even when one LLM call is slow.
 */
const PHASE_INDEX = {
  pending: 0,
  scraping: 0,
  extracting_icp: 1,
  drafting_campaigns: 2,
};

function WizardLoading({ url, status }) {
  const { lang } = React.useContext(LangCtx);
  const phase = PHASE_INDEX[status] !== undefined ? PHASE_INDEX[status] : 0;

  const stages = [
    {
      label: t({id:'Mengakses & membaca website', en:'Reading website'}, lang),
      detail: [
        t({id:'Mendownload halaman utama…', en:'Downloading homepage…'}, lang),
        t({id:'Membersihkan konten HTML…', en:'Cleaning HTML…'}, lang),
        t({id:'Menyimpan teks bersih…', en:'Storing clean text…'}, lang),
      ],
    },
    {
      label: t({id:'Mengekstrak Business DNA + ICP', en:'Extracting Business DNA + ICP'}, lang),
      detail: [
        t({id:'Mengidentifikasi industri…', en:'Identifying industry…'}, lang),
        t({id:'Menentukan target market…', en:'Mapping target market…'}, lang),
        t({id:'Mendeteksi pain points & value props…', en:'Detecting pain points & value props…'}, lang),
        t({id:'Menyusun ICP persona…', en:'Drafting ICP persona…'}, lang),
      ],
    },
    {
      label: t({id:'Merancang 3 strategi kampanye', en:'Designing 3 campaign strategies'}, lang),
      detail: [
        t({id:'Strategi 1: Lead-Gen + Outreach…', en:'Strategy 1: Lead-Gen + Outreach…'}, lang),
        t({id:'Strategi 2: Inbound AI Agent…', en:'Strategy 2: Inbound AI Agent…'}, lang),
        t({id:'Strategi 3: Re-aktivasi Broadcast…', en:'Strategy 3: Re-activation Broadcast…'}, lang),
        t({id:'Menulis sample WhatsApp message…', en:'Writing sample WA message…'}, lang),
      ],
    },
    {
      label: t({id:'Menyiapkan hasil', en:'Preparing results'}, lang),
      detail: [t({id:'Hampir selesai…', en:'Almost there…'}, lang)],
    },
  ];

  // Rotate the detail line every 2s so the substep keeps changing even
  // when the LLM call hasn't returned yet — perceived activity matters.
  const [detailIdx, setDetailIdx] = useState(0);
  useEffect(() => {
    setDetailIdx(0);
    const itv = setInterval(() => {
      setDetailIdx((i) => (i + 1) % (stages[phase]?.detail.length || 1));
    }, 2000);
    return () => clearInterval(itv);
  }, [phase]);

  // Progress bar % approximation: each phase = 25%, plus partial fill
  // based on detailIdx within the phase.
  const phaseStart = phase * 25;
  const detailWeight = (detailIdx + 1) / ((stages[phase]?.detail.length || 1) + 1);
  const progress = Math.min(phaseStart + detailWeight * 25, 95);

  const agents = [
    { icon:'🔍', name:'Scout', role: t({id:'Membaca website', en:'Website reader'}, lang) },
    { icon:'🧬', name:'Analyst', role: t({id:'Ekstrak Business DNA', en:'Business DNA extractor'}, lang) },
    { icon:'🗺️', name:'Architect', role: t({id:'Rancang strategi', en:'Strategy designer'}, lang) },
    { icon:'✨', name:'Compiler', role: t({id:'Siapkan hasil', en:'Result compiler'}, lang) },
  ];

  return (
    <section className="section wizard-loading-section" style={{background:'var(--paper)'}}>
      <div className="wrap" style={{maxWidth:680}}>

        {/* Header */}
        <div style={{textAlign:'center', marginBottom:40}}>
          <div style={{display:'inline-flex', alignItems:'center', gap:8, marginBottom:16,
            background:'#fff', border:'1px solid var(--border)', borderRadius:99,
            padding:'6px 16px 6px 10px', fontSize:12, fontWeight:600
          }}>
            <span style={{
              width:8, height:8, borderRadius:99, background:'var(--gm)',
              display:'inline-block', animation:'wizard-pulse 1.2s ease-in-out infinite'
            }}/>
            <span style={{color:'var(--gm)', letterSpacing:'.06em'}}>
              {t({id:'LIVE · MENGANALISIS', en:'LIVE · ANALYZING'}, lang)}
            </span>
          </div>
          {url && (
            <div style={{
              fontFamily:'var(--mono)', fontSize:13, color:'var(--muted)',
              background:'#fff', border:'1px solid var(--border)',
              borderRadius:8, padding:'8px 16px', display:'inline-block',
              maxWidth:'100%', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'
            }}>
              {url}
            </div>
          )}
        </div>

        {/* Agent cards */}
        <div style={{display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:12, marginBottom:32}}>
          {agents.map((a, i) => {
            const isDone = i < phase;
            const isActive = i === phase;
            return (
              <div key={i} style={{
                background:'#fff',
                border: isActive ? '2px solid var(--gm)' : isDone ? '1px solid #d1fae5' : '1px solid var(--border)',
                borderRadius:14, padding:'20px 12px', textAlign:'center',
                boxShadow: isActive ? '0 0 28px rgba(234,0,140,0.12)' : isDone ? '0 2px 8px rgba(34,197,94,0.08)' : 'none',
                transition:'all 0.4s ease', position:'relative', overflow:'hidden'
              }}>
                {isDone && (
                  <div style={{
                    position:'absolute', top:8, right:8,
                    width:18, height:18, borderRadius:99,
                    background:'#22c55e', color:'#fff',
                    fontSize:10, fontWeight:700,
                    display:'flex', alignItems:'center', justifyContent:'center'
                  }}>✓</div>
                )}
                <div style={{fontSize:26, marginBottom:10}}>{a.icon}</div>
                <div style={{
                  fontSize:12, fontWeight:700, letterSpacing:'.04em',
                  color: isActive ? 'var(--gm)' : isDone ? '#16a34a' : 'var(--muted)',
                  marginBottom:4
                }}>{a.name}</div>
                <div style={{fontSize:10, color:'var(--muted)', lineHeight:1.4, marginBottom: isActive ? 8 : 0}}>{a.role}</div>
                {isActive && (
                  <div style={{
                    fontSize:10, color:'var(--gm)', fontFamily:'var(--mono)',
                    background:'oklch(98% 0.01 330)', borderRadius:6, padding:'4px 8px',
                    lineHeight:1.5, wordBreak:'break-word'
                  }} key={detailIdx}>
                    {stages[phase].detail[detailIdx % stages[phase].detail.length]}
                  </div>
                )}
                {isActive && (
                  <div style={{
                    position:'absolute', bottom:0, left:0, right:0, height:3,
                    background:'var(--grad)', borderRadius:'0 0 2px 2px',
                    animation:'wizard-progress-anim 2s ease-in-out infinite'
                  }}/>
                )}
              </div>
            );
          })}
        </div>

        {/* Progress bar */}
        <div className="wizard-progress" aria-hidden>
          <div className="wizard-progress-fill" style={{width: `${progress}%`}}/>
          <div className="wizard-progress-shimmer"/>
        </div>

        <div className="wizard-loading-foot">
          {t({id:'Gaung AI memproses website kamu secara real-time — biasanya selesai dalam 20–40 detik.', en:'Gaung AI processes your website in real-time — typically done in 20–40 seconds.'}, lang)}
        </div>
      </div>
    </section>
  );
}

function DnaField({ label, value }) {
  return (
    <div>
      <div className="eyebrow" style={{marginBottom:6}}>{label}</div>
      <div style={{fontSize:14}}>{value}</div>
    </div>
  );
}

function DnaList({ label, items }) {
  return (
    <div>
      <div className="eyebrow" style={{marginBottom:6}}>{label}</div>
      <ul style={{margin:0, paddingLeft:18, fontSize:13.5, lineHeight:1.55, color:'var(--ink)'}}>
        {items.slice(0,4).map((it, i) => <li key={i}>{it}</li>)}
      </ul>
    </div>
  );
}

/**
 * M63 — Wizard leads preview. Renders one of 5 states:
 *   - disabled / null: hide section entirely (feature off)
 *   - pending / hunting: skeleton loader "AI sedang mencari lead untuk Anda…"
 *   - ready / cached: grid of 10 leads, hot matches highlighted
 *   - budget_exhausted: CTA tease ("Daftar untuk akses leads")
 *   - failed: hide (gracefully degrade)
 *
 * Lead nomor WA dimasking server-side ("+62 8••••••••89"). Full number
 * hanya muncul di dashboard tenant yang sudah berlangganan.
 */
function LeadsPreviewSection({ preview, lang }) {
  if (!preview) return null;
  const { status, total_found, verified_count, leads } = preview;
  if (status === 'disabled' || status === 'failed') return null;

  const isLoading = status === 'pending' || status === 'hunting';
  const isReady = status === 'ready' || status === 'cached';
  const isBudgetExhausted = status === 'budget_exhausted';

  return (
    <div style={{margin:'48px 0 0', padding:'32px 24px', background:'linear-gradient(135deg, #fff8f3 0%, #fff5ee 100%)', border:'1px solid #ffd9b8', borderRadius:20}}>
      <div style={{textAlign:'center', marginBottom:24}}>
        <div style={{fontSize:11, color:'#ea008c', fontWeight:700, letterSpacing:'.12em', textTransform:'uppercase', marginBottom:8}}>
          {t({id:'🎯 Hasil Lead Generation', en:'🎯 Lead Generation Results'}, lang)}
        </div>
        {isLoading && (
          <h2 className="h-section" style={{marginBottom:8}}>
            {t({id:'AI sedang mencari calon customer untuk Anda…', en:'AI is finding potential customers for you…'}, lang)}
          </h2>
        )}
        {isReady && verified_count > 0 && (
          <>
            <h2 className="h-section" style={{marginBottom:8}}>
              {t({
                id:`${verified_count} calon customer dengan WhatsApp aktif`,
                en:`${verified_count} potential customers with active WhatsApp`
              }, lang)}
            </h2>
            <p className="lead" style={{maxWidth:520, margin:'0 auto'}}>
              {t({
                id:`Sudah kami siapkan untuk Anda. Daftar untuk akses nomor lengkap mereka.`,
                en:`We've prepared them for you. Sign up to access their full numbers.`
              }, lang)}
            </p>
          </>
        )}
        {isBudgetExhausted && (
          <h2 className="h-section" style={{marginBottom:8}}>
            {t({id:'Daftar untuk akses lead potensial Anda', en:'Sign up to access your potential leads'}, lang)}
          </h2>
        )}
      </div>

      {isLoading && <LeadsSkeletonGrid/>}
      {isReady && Array.isArray(leads) && leads.length > 0 && (
        <LeadsGrid leads={leads} lang={lang}/>
      )}
      {isBudgetExhausted && (
        <div style={{textAlign:'center', padding:'24px 12px', color:'var(--muted)'}}>
          <p>{t({id:'Slot lead preview hari ini sudah penuh. Daftar sekarang untuk dapat 47+ lead langsung di dashboard.', en:'Today\'s preview slots are full. Sign up now to get 47+ leads directly in your dashboard.'}, lang)}</p>
        </div>
      )}

      {isReady && (
        <div style={{marginTop:20, paddingTop:16, borderTop:'1px solid #ffd9b8', textAlign:'center'}}>
          <p style={{fontSize:11.5, color:'var(--muted)', lineHeight:1.55, maxWidth:500, margin:'0 auto'}}>
            {t({
              id:'Data diambil dari profil bisnis publik. Bisnis-bisnis ini secara sadar mempublikasikan WhatsApp mereka untuk dihubungi calon customer. Nomor lengkap akan tersedia setelah Anda berlangganan.',
              en:'Data from public business profiles where businesses voluntarily published WhatsApp contact info. Full numbers available after subscription.'
            }, lang)}
          </p>
        </div>
      )}
    </div>
  );
}

function LeadsSkeletonGrid() {
  const items = [0,1,2,3,4,5];
  return (
    <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(260px, 1fr))', gap:14}}>
      {items.map((i) => (
        <div key={i} style={{
          background:'#fff', borderRadius:12, padding:16,
          border:'1px solid #f0e6d9',
          animation:`pulse 1.5s ease-in-out ${i*0.1}s infinite`,
          minHeight:110,
        }}>
          <div style={{width:'70%', height:14, background:'#f0e6d9', borderRadius:4, marginBottom:8}}/>
          <div style={{width:'40%', height:11, background:'#f5ede0', borderRadius:4, marginBottom:14}}/>
          <div style={{width:'85%', height:11, background:'#f5ede0', borderRadius:4}}/>
        </div>
      ))}
      <style>{`@keyframes pulse { 0%,100% { opacity: 1 } 50% { opacity: .5 } }`}</style>
    </div>
  );
}

function LeadsGrid({ leads, lang }) {
  const hot = leads.filter((l) => l.is_hot_match);
  const others = leads.filter((l) => !l.is_hot_match);

  return (
    <>
      {hot.length > 0 && (
        <>
          <div style={{fontSize:11, color:'#ea008c', fontWeight:700, letterSpacing:'.1em', textTransform:'uppercase', marginBottom:12, textAlign:'center'}}>
            🔥 {t({id:'Hot Match — Paling Cocok untuk Bisnis Anda', en:'Hot Match — Best Fit for Your Business'}, lang)}
          </div>
          <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(260px, 1fr))', gap:14, marginBottom:24}}>
            {hot.map((lead, i) => <LeadCard key={i} lead={lead} hot/>)}
          </div>
        </>
      )}
      {others.length > 0 && (
        <>
          <div style={{fontSize:11, color:'var(--muted)', fontWeight:700, letterSpacing:'.1em', textTransform:'uppercase', marginBottom:12, textAlign:'center'}}>
            📋 {t({id:'Calon Potensial Lainnya', en:'Other Potential Candidates'}, lang)}
          </div>
          <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(220px, 1fr))', gap:12}}>
            {others.map((lead, i) => <LeadCard key={i} lead={lead}/>)}
          </div>
        </>
      )}
    </>
  );
}

function LeadCard({ lead, hot }) {
  return (
    <div style={{
      background:'#fff',
      border: hot ? '1.5px solid #ea008c' : '1px solid #f0e6d9',
      borderRadius:12,
      padding: hot ? 16 : 14,
      position:'relative',
      boxShadow: hot ? '0 4px 12px rgba(234,0,140,0.08)' : 'none',
    }}>
      <div style={{fontWeight:600, fontSize: hot ? 14.5 : 13.5, marginBottom:6, lineHeight:1.3, color:'var(--ink)'}}>
        {lead.name}
      </div>
      <div style={{display:'flex', flexWrap:'wrap', gap:8, fontSize:11.5, color:'var(--muted)', marginBottom:10}}>
        {lead.city && <span>{lead.city}</span>}
        {lead.rating && lead.review_count > 0 && (
          <span>⭐ {lead.rating.toFixed(1)} ({lead.review_count})</span>
        )}
      </div>
      <div style={{
        display:'inline-flex', alignItems:'center', gap:6,
        padding:'4px 10px',
        background:'#f0f9eb', border:'1px solid #cfe8b9', borderRadius:99,
        fontSize:11, fontWeight:600, color:'#3a7a18',
      }}>
        ✓ WA aktif: <span style={{fontFamily:'monospace', letterSpacing:'.5px'}}>{lead.wa_masked}</span>
      </div>
    </div>
  );
}

const PLAN_META = {
  free:       { name: 'Free',       nameEn: 'Free',       price: 'Rp 0',         priceSub: '',        subEn: '' },
  starter:    { name: 'Starter',    nameEn: 'Starter',    price: 'Rp 3.000.000', priceSub: '/bulan',  subEn: '/month' },
  business:   { name: 'Bisnis',     nameEn: 'Business',   price: 'Rp 8.000.000', priceSub: '/bulan',  subEn: '/month' },
};

function PlanRecommendationCard({ plan, reasoning, lang, sessionId }) {
  const meta = PLAN_META[plan];
  if (!meta) return null; // guard: missing or invalid plan

  const isId = lang === 'id' || !lang;
  const planName  = isId ? meta.name    : meta.nameEn;
  const priceSub  = isId ? meta.priceSub : meta.subEn;
  const headline  = isId
    ? `AI merekomendasikan paket ${planName} untuk bisnis Anda`
    : `AI recommends the ${planName} plan for your business`;
  const ctaText   = isId ? `Mulai paket ${planName}` : `Start ${planName} plan`;
  // dashboard.gaung.app is the CUSTOMER app (office.gaung.app is the internal
  // team cockpit — sending prospects there was a bug). Carry the wizard session
  // so Brand DNA + campaigns prefill instead of re-asking for the URL.
  const signupUrl = sessionId
    ? `https://dashboard.gaung.app/signup?plan=${plan}&wizard=${sessionId}`
    : `https://dashboard.gaung.app/signup?plan=${plan}`;

  return (
    <div style={{
      marginTop: 32,
      padding: '24px 28px',
      borderRadius: 16,
      background: 'linear-gradient(135deg, #f0f4ff 0%, #faf5ff 100%)',
      border: '1.5px solid #c7d4f8',
      boxShadow: '0 2px 12px rgba(99,102,241,0.08)',
    }}>
      <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#6366f1', marginBottom: 8 }}>
        {isId ? '✦ Rekomendasi AI' : '✦ AI Recommendation'}
      </div>
      <div style={{ fontSize: 20, fontWeight: 700, color: '#1a1a2e', marginBottom: 4 }}>
        {headline}
      </div>
      <div style={{ fontSize: 24, fontWeight: 800, color: '#6366f1', marginBottom: reasoning ? 12 : 16 }}>
        {meta.price}<span style={{ fontSize: 14, fontWeight: 500, color: '#64748b' }}>{priceSub}</span>
      </div>
      {reasoning && (
        <p style={{ fontSize: 14, color: '#374151', lineHeight: 1.6, margin: '0 0 16px' }}>
          {reasoning}
        </p>
      )}
      <a
        href={signupUrl}
        className="btn btn-grad"
        style={{ display: 'inline-block', textDecoration: 'none' }}
      >
        {ctaText}
      </a>
    </div>
  );
}

function EmailResultCta({ sessionId }) {
  const { lang } = React.useContext(LangCtx);
  const [open, setOpen] = useState(false);
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [done, setDone] = useState(false);
  const [error, setError] = useState(null);

  async function submit(e) {
    e.preventDefault();
    if (!email.trim()) return;
    setSubmitting(true);
    setError(null);
    try {
      const res = await fetch(`${ORCH_URL}/v1/public/wizard/${sessionId}/email`, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        // US-1.2 — send email always; include WhatsApp number when given so the
        // backend also pushes a WA 1-pager.
        body: JSON.stringify({ email: email.trim(), ...(phone.trim() ? { phone: phone.trim() } : {}) }),
      });
      const body = await res.json().catch(() => ({}));
      if (!res.ok) {
        if (res.status === 429) {
          setError(t({id:'Sudah maksimum 3 kirim untuk sesi ini. Coba besok.', en:'Maximum 3 sends per session reached. Try tomorrow.'}, lang));
        } else if (res.status === 503) {
          setError(t({id:'Sistem email belum siap. Hubungi WhatsApp kami.', en:'Email system not ready. Contact us on WhatsApp.'}, lang));
        } else {
          setError(body?.message ?? `Error ${res.status}`);
        }
        setSubmitting(false);
        return;
      }
      setDone(true);
    } catch (err) {
      setError(err.message);
    } finally {
      setSubmitting(false);
    }
  }

  if (done) {
    return (
      <div style={{
        marginTop:32, marginBottom:8, padding:'20px 24px',
        background:'oklch(98% 0.015 145)', border:'1px solid oklch(85% 0.05 145)', borderRadius:14,
        textAlign:'center', maxWidth:560, marginLeft:'auto', marginRight:'auto',
      }}>
        <div style={{fontSize:24, marginBottom:6}}>✉️</div>
        <div style={{fontSize:14, fontWeight:600, color:'oklch(35% 0.12 145)'}}>
          {t({id:'Hasil dikirim ke ', en:'Sent to '}, lang)}<strong>{email}</strong>
          {phone.trim() ? t({id:' + WhatsApp', en:' + WhatsApp'}, lang) : ''}
        </div>
        <div style={{fontSize:12, color:'#666', marginTop:6}}>
          {phone.trim()
            ? t({id:'Cek inbox email (1-2 menit) + WhatsApp Anda. Tidak ketemu email? Cek folder Spam/Promotions.', en:'Check your email (1-2 min) + WhatsApp. No email? Check Spam/Promotions.'}, lang)
            : t({id:'Cek inbox dalam 1-2 menit. Tidak ketemu? Cek folder Spam/Promotions.', en:'Check your inbox in 1-2 minutes. Not there? Check Spam/Promotions folder.'}, lang)}
        </div>
      </div>
    );
  }

  if (!open) {
    return (
      <div style={{
        marginTop:32, marginBottom:24, padding:'18px 24px',
        background:'oklch(97% 0.012 70)', border:'1px dashed oklch(85% 0.02 70)', borderRadius:14,
        textAlign:'center', maxWidth:560, marginLeft:'auto', marginRight:'auto',
      }}>
        <div style={{fontSize:14, color:'#444', marginBottom:10, lineHeight:1.5}}>
          {t({
            id:'📧 Mau terima hasil analisa ini via email + WhatsApp untuk dishare ke partner/CFO/CEO?',
            en:'📧 Want this analysis via email + WhatsApp to share with your partner/CFO/CEO?',
          }, lang)}
        </div>
        <button
          type="button"
          onClick={() => setOpen(true)}
          style={{
            background:'#fff', border:'1.5px solid #ea008c', color:'#ea008c',
            padding:'8px 20px', borderRadius:99, fontSize:13, fontWeight:600, cursor:'pointer',
          }}
        >
          {t({id:'Kirim ke email + WhatsApp', en:'Send to email + WhatsApp'}, lang)}
        </button>
      </div>
    );
  }

  return (
    <div style={{
      marginTop:32, marginBottom:24, padding:'24px 28px',
      background:'#fff', border:'1px solid #ebe7e0', borderRadius:14,
      maxWidth:560, marginLeft:'auto', marginRight:'auto',
    }}>
      <div style={{fontSize:15, fontWeight:600, marginBottom:6}}>
        {t({id:'Kirim hasil ke email + WhatsApp', en:'Send this analysis to your email + WhatsApp'}, lang)}
      </div>
      <div style={{fontSize:12, color:'#666', marginBottom:14, lineHeight:1.5}}>
        {t({
          id:'1-pager lengkap (Business DNA + ICP) via email. Isi nomor WhatsApp (opsional) untuk terima ringkasan + link via WA juga. Tidak ada spam.',
          en:'A complete 1-pager (Business DNA + ICP) via email. Add your WhatsApp number (optional) to also get a summary + link on WA. No spam.',
        }, lang)}
      </div>
      <form onSubmit={submit} style={{display:'flex', flexDirection:'column', gap:8}}>
        <input
          type="email"
          required
          autoFocus
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder={t({id:'nama@perusahaan.com', en:'name@company.com'}, lang)}
          style={{
            padding:'10px 14px', fontSize:14,
            border:'1px solid #ddd', borderRadius:8, background:'#fff',
            fontFamily:'inherit', outline:'none',
          }}
        />
        <input
          type="tel"
          value={phone}
          onChange={(e) => setPhone(e.target.value)}
          placeholder={t({id:'No. WhatsApp (opsional) — cth: 0812xxxx', en:'WhatsApp number (optional) — e.g. 0812xxxx'}, lang)}
          style={{
            padding:'10px 14px', fontSize:14,
            border:'1px solid #ddd', borderRadius:8, background:'#fff',
            fontFamily:'inherit', outline:'none',
          }}
        />
        <button
          type="submit"
          disabled={submitting || !email.trim()}
          style={{
            padding:'11px 18px', fontSize:13, fontWeight:600,
            background: submitting ? '#999' : 'linear-gradient(90deg,#ea008c,#ff8a10)',
            color:'#fff', border:0, borderRadius:8, cursor:submitting?'wait':'pointer',
          }}
        >
          {submitting ? t({id:'Mengirim…',en:'Sending…'}, lang) : t({id:'Kirim ke saya', en:'Send to me'}, lang)}
        </button>
      </form>
      {error && <div style={{color:'#c00', fontSize:12, marginTop:10}}>{error}</div>}
      <div style={{textAlign:'right', marginTop:6}}>
        <button
          type="button"
          onClick={() => { setOpen(false); setEmail(''); setError(null); }}
          style={{background:'none', border:0, color:'#999', fontSize:11, cursor:'pointer'}}
        >
          {t({id:'Batal', en:'Cancel'}, lang)}
        </button>
      </div>
    </div>
  );
}

/**
 * F-038 — WhatsApp share CTA. Renders a button that opens WhatsApp with a
 * pre-filled, user-editable message containing the user's OWN business
 * analysis (business name, lead potential). Uses `wa.me/?text=...` (no
 * recipient phone), so user picks who to send to themselves — we never
 * process third-party PII. UTM `?utm_source=wa_share` is campaign-level
 * only (no recipient_id, no fingerprinting) per UU PDP compliance.
 *
 * Message style is intentionally "testimonial pribadi", not "iklan korporat",
 * to comply with WhatsApp Business ToS for unsolicited promotional content.
 */
function WhatsAppShareCta({ businessName, leadsCount, industry }) {
  const { lang } = React.useContext(LangCtx);
  const [open, setOpen] = useState(false);

  const defaultMsg = t({
    id: `Lagi iseng cek bisnis aku (${businessName}) pakai Gaung AI — ternyata ada potensi ${leadsCount} leads di pasar yang belum kesentuh. Lumayan eye-opening 👀\n\nKamu coba juga deh, gratis dan cepat (~30 detik): https://gaung.app/?utm_source=wa_share`,
    en: `Just checked my business (${businessName}) using Gaung AI — turns out there are ${leadsCount} untapped leads in the market. Pretty eye-opening 👀\n\nYou should try it too, free and quick (~30s): https://gaung.app/?utm_source=wa_share`,
  }, lang);

  const [msg, setMsg] = useState(defaultMsg);

  function sendToWhatsApp() {
    const url = `https://wa.me/?text=${encodeURIComponent(msg)}`;
    window.open(url, '_blank', 'noopener');
  }

  if (!open) {
    return (
      <div style={{
        marginTop:16, marginBottom:24, padding:'18px 24px',
        background:'oklch(97.5% 0.025 145)', border:'1px dashed oklch(80% 0.08 145)', borderRadius:14,
        textAlign:'center', maxWidth:560, marginLeft:'auto', marginRight:'auto',
      }}>
        <div style={{fontSize:14, color:'#444', marginBottom:10, lineHeight:1.5}}>
          {t({
            id:'💬 Hasil ini menarik? Share ke temen sesama owner — mungkin bisnis mereka juga punya leads tersembunyi.',
            en:'💬 Find this useful? Share with fellow business owners — they might also have hidden leads.',
          }, lang)}
        </div>
        <button
          type="button"
          onClick={() => setOpen(true)}
          style={{
            background:'#25D366', border:'1.5px solid #25D366', color:'#fff',
            padding:'8px 20px', borderRadius:99, fontSize:13, fontWeight:600, cursor:'pointer',
            display:'inline-flex', alignItems:'center', gap:8,
          }}
        >
          <span style={{fontSize:16, lineHeight:1}}>📱</span>
          {t({id:'Share ke WhatsApp', en:'Share to WhatsApp'}, lang)}
        </button>
      </div>
    );
  }

  return (
    <div style={{
      marginTop:16, marginBottom:24, padding:'24px 28px',
      background:'#fff', border:'1px solid #ebe7e0', borderRadius:14,
      maxWidth:560, marginLeft:'auto', marginRight:'auto',
    }}>
      <div style={{fontSize:15, fontWeight:600, marginBottom:6}}>
        {t({id:'Share hasil ke WhatsApp', en:'Share to WhatsApp'}, lang)}
      </div>
      <div style={{fontSize:12, color:'#666', marginBottom:14, lineHeight:1.5}}>
        {t({
          id:'Edit pesannya kalau mau, lalu pilih sendiri mau kirim ke siapa.',
          en:'Edit the message if you like, then pick the recipient yourself.',
        }, lang)}
      </div>
      <textarea
        value={msg}
        onChange={(e) => setMsg(e.target.value)}
        rows={6}
        style={{
          width:'100%', padding:'12px 14px', fontSize:13, lineHeight:1.55,
          border:'1px solid #ddd', borderRadius:8, background:'#fff',
          fontFamily:'inherit', outline:'none', resize:'vertical', boxSizing:'border-box',
        }}
      />
      <div style={{display:'flex', gap:8, marginTop:12, justifyContent:'flex-end'}}>
        <button
          type="button"
          onClick={() => { setOpen(false); setMsg(defaultMsg); }}
          style={{
            background:'none', border:'1px solid #ddd', color:'#666',
            padding:'9px 18px', fontSize:13, fontWeight:500, borderRadius:8, cursor:'pointer',
          }}
        >
          {t({id:'Batal', en:'Cancel'}, lang)}
        </button>
        <button
          type="button"
          onClick={sendToWhatsApp}
          disabled={!msg.trim()}
          style={{
            background:'#25D366', color:'#fff', border:0,
            padding:'9px 22px', fontSize:13, fontWeight:600, borderRadius:8, cursor:'pointer',
            display:'inline-flex', alignItems:'center', gap:8,
          }}
        >
          <span style={{fontSize:14, lineHeight:1}}>📱</span>
          {t({id:'Buka WhatsApp', en:'Open WhatsApp'}, lang)}
        </button>
      </div>
    </div>
  );
}

function CampaignCard({ campaign, selected, onSelect }) {
  const { lang } = React.useContext(LangCtx);
  const badge = strategyLabel(campaign.strategy, lang);
  return (
    <button
      type="button"
      onClick={onSelect}
      className="campaign-card"
      style={{
        textAlign: 'left',
        background: 'transparent',
        border: selected ? '2px solid var(--gm)' : undefined,
        boxShadow: selected ? '0 0 0 4px rgba(234,0,140,0.12)' : undefined,
        cursor: 'pointer',
        font: 'inherit',
        color: 'inherit',
      }}
    >
      <div className="campaign-card-head">
        <span className="campaign-card-badge">{badge}</span>
        <span style={{fontSize:12, color:'var(--muted)', fontFamily:'var(--mono)'}}>0{campaign.id}</span>
      </div>
      <div className="campaign-card-title">{campaign.title}</div>
      <p className="campaign-card-why">{campaign.why}</p>
      <div className="campaign-card-meta">
        <div className="eyebrow" style={{marginBottom:4}}>{t({id:'Audience', en:'Audience'}, lang)}</div>
        <div style={{fontSize:13}}>{campaign.audience}</div>
      </div>
      <div style={{fontSize:12, color:'var(--muted)', marginBottom:14}}>{campaign.expected_outcome}</div>
      <div className="campaign-card-cta">
        <span style={{color:'var(--gm)', fontWeight:600, fontSize:13}}>
          {selected
            ? t({id:'✓ Dipilih — isi form di bawah', en:'✓ Selected — fill form below'}, lang)
            : t({id:'Pilih kampanye ini', en:'Pick this campaign'}, lang)}
        </span>
        <span style={{color:'var(--gm)', fontSize:18}}>{selected ? '↓' : '→'}</span>
      </div>
    </button>
  );
}


function strategyLabel(s, lang) {
  if (s === 'lead_gen_outbound') return t({id:'Lead-Gen + Outreach', en:'Lead-Gen + Outreach'}, lang);
  if (s === 'inbound_ai_agent') return t({id:'Inbound AI Agent', en:'Inbound AI Agent'}, lang);
  if (s === 'reactivation_broadcast') return t({id:'Re-aktivasi Broadcast', en:'Re-activation Broadcast'}, lang);
  return s;
}

function truncate(s, n) { return s.length > n ? s.slice(0, n-1) + '…' : s; }

function getMarketInsights(icp) {
  const ind = ((icp && icp.industry) || '').toLowerCase();
  if (ind.includes('properti') || ind.includes('real estat') || ind.includes('property')) {
    return { leads:'14.200+', market:'Rp 8,7T', deal:'Rp 920jt', region:'Seluruh Indonesia' };
  }
  if (ind.includes('teknologi') || ind.includes('software') || ind.includes('saas')) {
    return { leads:'11.800+', market:'Rp 4,1T', deal:'Rp 130jt', region:'Asia Tenggara' };
  }
  if (ind.includes('pendidikan') || ind.includes('edukasi') || ind.includes('education') || ind.includes('kursus')) {
    return { leads:'28.000+', market:'Rp 2,1T', deal:'Rp 22jt', region:'Jawa–Bali' };
  }
  if (ind.includes('klinik') || ind.includes('kesehatan') || ind.includes('health') || ind.includes('medis')) {
    return { leads:'9.500+', market:'Rp 1,6T', deal:'Rp 28jt', region:'Urban Besar' };
  }
  if (ind.includes('manufaktur') || ind.includes('manufacturing') || ind.includes('pabrik')) {
    return { leads:'4.800+', market:'Rp 7,2T', deal:'Rp 340jt', region:'Jawa–Sulawesi' };
  }
  if (ind.includes('retail') || ind.includes('ritel') || ind.includes('distributor')) {
    return { leads:'18.500+', market:'Rp 3,8T', deal:'Rp 45jt', region:'Seluruh Indonesia' };
  }
  if (ind.includes('hotel') || ind.includes('hospitality') || ind.includes('restoran') || ind.includes('wisata')) {
    return { leads:'12.000+', market:'Rp 1,9T', deal:'Rp 52jt', region:'Destinasi Utama' };
  }
  if (ind.includes('keuangan') || ind.includes('finance') || ind.includes('fintech') || ind.includes('asuransi')) {
    return { leads:'21.000+', market:'Rp 12,4T', deal:'Rp 180jt', region:'Seluruh Indonesia' };
  }
  return { leads:'8.500+', market:'Rp 2,4T', deal:'Rp 68jt', region:'Jawa–Bali' };
}

// Mozart floating button — fixed bottom-right, small round.
// Safari blocks useEffect-initiated play(); the button is the primary trigger there.
// Shows a tooltip on hover so users know what it is.
function WizardSoundtrack({ playing, onToggle, lang }) {
  const [hovered, setHovered] = useState(false);
  return (
    <div
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{position:'fixed', bottom:24, right:24, zIndex:300, display:'flex', flexDirection:'column', alignItems:'center', gap:6}}
    >
      {hovered && (
        <div style={{
          background:'rgba(20,20,20,0.85)', color:'#fff', borderRadius:8,
          padding:'6px 10px', fontSize:10, fontFamily:'var(--mono)',
          whiteSpace:'nowrap', pointerEvents:'none',
          backdropFilter:'blur(4px)'
        }}>
          Mozart · Le Nozze di Figaro
        </div>
      )}
      <button
        onClick={onToggle}
        aria-label={playing ? 'Pause music' : 'Play music'}
        style={{
          width:44, height:44, borderRadius:99, cursor:'pointer',
          border: playing ? 'none' : '1.5px solid var(--border)',
          background: playing ? 'var(--gm)' : '#fff',
          boxShadow: playing
            ? '0 4px 20px rgba(234,0,140,0.35)'
            : '0 4px 16px rgba(0,0,0,0.12)',
          display:'flex', alignItems:'center', justifyContent:'center',
          fontSize:16, color: playing ? '#fff' : 'var(--ink)',
          transition:'all 0.2s ease', outline:'none'
        }}
      >
        {playing ? '❚❚' : '♪'}
      </button>
    </div>
  );
}

// ---- Hero dashboard mock --------------------------------
function HeroDashMock() {
  const { lang } = React.useContext(LangCtx);
  return (
    <div style={{
      background:'var(--dark)', color:'var(--dark-ink)',
      border:'1px solid var(--dark-line)', borderRadius:16,
      padding: 20, position:'relative', overflow:'hidden',
      boxShadow:'0 40px 80px -20px rgba(234, 0, 140, 0.18), 0 20px 40px -10px rgba(0,0,0,0.2)'
    }}>
      {/* top chrome */}
      <div style={{display:'flex',alignItems:'center',gap:10,paddingBottom:14,borderBottom:'1px solid var(--dark-line)'}}>
        <div style={{display:'flex',gap:6}}>
          <span style={{width:10,height:10,borderRadius:99,background:'#ff6b6b'}}/>
          <span style={{width:10,height:10,borderRadius:99,background:'#ffd166'}}/>
          <span style={{width:10,height:10,borderRadius:99,background:'#51cf66'}}/>
        </div>
        <div style={{fontFamily:'var(--mono)', fontSize:11, color:'oklch(65% 0.008 70)', marginLeft:8}}>dashboard.gaung.app</div>
        <div style={{marginLeft:'auto', display:'flex', gap:8, alignItems:'center'}}>
          <span style={{fontSize:10, padding:'3px 8px', background:'var(--grad)', color:'#fff', borderRadius:99, fontWeight:600}}>LIVE</span>
          <span style={{fontSize:11, color:'oklch(70% 0.008 70)'}}>{t({id:'Sinkron 12 dtk lalu', en:'Synced 12s ago'}, lang)}</span>
        </div>
      </div>

      {/* KPI row */}
      <div className="dash-kpi" style={{display:'grid',gap:12,marginTop:20}}>
        {[
          { l: t({id:'Lead masuk', en:'Leads in'}, lang), v:'2,847', d:'+12.4%' },
          { l: t({id:'Balasan WA', en:'WA replies'}, lang), v:'968', d:'+38%' },
          { l: t({id:'Meeting ter-booking', en:'Meetings booked'}, lang), v:'142', d:'+24%' },
          { l: t({id:'Pipeline value', en:'Pipeline value'}, lang), v:'IDR 4.2B', d:'+19%' },
        ].map((k,i) => (
          <div key={i} style={{background:'var(--dark-2)',borderRadius:10,padding:'14px 16px',border:'1px solid var(--dark-line)'}}>
            <div style={{fontSize:10,color:'oklch(65% 0.008 70)',textTransform:'uppercase',letterSpacing:'.08em',fontWeight:600}}>{k.l}</div>
            <div style={{fontSize:26,fontWeight:500,letterSpacing:'-0.02em',marginTop:4}}>{k.v}</div>
            <div style={{fontSize:11,color:'#51cf66',marginTop:2}}>↑ {k.d}</div>
          </div>
        ))}
      </div>

      {/* chart zone */}
      <div className="dash-chart-grid" style={{display:'grid',gap:12,marginTop:12}}>
        <div style={{background:'var(--dark-2)',borderRadius:10,padding:18,border:'1px solid var(--dark-line)',minHeight:180}}>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:16}}>
            <div>
              <div style={{fontSize:13,fontWeight:500}}>{t({id:'Lead flow 30 hari', en:'Lead flow, 30 days'}, lang)}</div>
              <div style={{fontSize:11,color:'oklch(65% 0.008 70)',marginTop:2}}>{t({id:'WhatsApp + Email', en:'WhatsApp + Email'}, lang)}</div>
            </div>
            <div style={{display:'flex',gap:8,fontSize:10}}>
              <span style={{display:'flex',alignItems:'center',gap:4,color:'oklch(70% 0.008 70)'}}>
                <span style={{width:8,height:8,borderRadius:2,background:'#ea008c'}}/>WA
              </span>
              <span style={{display:'flex',alignItems:'center',gap:4,color:'oklch(70% 0.008 70)'}}>
                <span style={{width:8,height:8,borderRadius:2,background:'#ff8a10'}}/>Email
              </span>
            </div>
          </div>
          <svg viewBox="0 0 400 120" width="100%" height="120" preserveAspectRatio="none">
            <defs>
              <linearGradient id="hgm" x1="0" x2="0" y1="0" y2="1">
                <stop offset="0" stopColor="#ea008c" stopOpacity="0.35"/>
                <stop offset="1" stopColor="#ea008c" stopOpacity="0"/>
              </linearGradient>
              <linearGradient id="hgo" x1="0" x2="0" y1="0" y2="1">
                <stop offset="0" stopColor="#ff8a10" stopOpacity="0.3"/>
                <stop offset="1" stopColor="#ff8a10" stopOpacity="0"/>
              </linearGradient>
            </defs>
            <path d="M0,90 C40,80 60,60 100,55 C140,50 160,70 200,50 C240,30 260,40 300,25 C340,10 360,20 400,10 L400,120 L0,120 Z" fill="url(#hgm)"/>
            <path d="M0,90 C40,80 60,60 100,55 C140,50 160,70 200,50 C240,30 260,40 300,25 C340,10 360,20 400,10" stroke="#ea008c" strokeWidth="1.6" fill="none"/>
            <path d="M0,100 C40,95 80,90 120,80 C160,70 200,85 240,70 C280,55 320,65 360,50 C380,45 400,48 400,48 L400,120 L0,120 Z" fill="url(#hgo)"/>
            <path d="M0,100 C40,95 80,90 120,80 C160,70 200,85 240,70 C280,55 320,65 360,50 C380,45 400,48 400,48" stroke="#ff8a10" strokeWidth="1.6" fill="none"/>
          </svg>
        </div>

        {/* Live conversation feed */}
        <div style={{background:'var(--dark-2)',borderRadius:10,padding:18,border:'1px solid var(--dark-line)'}}>
          <div style={{fontSize:13,fontWeight:500,marginBottom:12}}>{t({id:'Conversation Engine', en:'Conversation Engine'}, lang)}</div>
          {[
            { n:'Budi S.', msg: t({id:'Berapa harga paket Business?', en:'Price for the Business plan?'}, lang), tag:'hot' },
            { n:'Rina K.', msg: t({id:'Bisa demo minggu ini?', en:'Can we demo this week?'}, lang), tag:'hot' },
            { n:'PT Merdeka', msg: t({id:'Kirim proposal', en:'Send proposal'}, lang), tag:'warm' },
          ].map((c,i)=> (
            <div key={i} style={{display:'flex',gap:10,padding:'8px 0',borderTop:i?'1px solid var(--dark-line)':'none'}}>
              <div style={{width:28,height:28,borderRadius:99,background:'var(--grad)',color:'#fff',display:'flex',alignItems:'center',justifyContent:'center',fontSize:11,fontWeight:600,flexShrink:0}}>
                {c.n[0]}
              </div>
              <div style={{flex:1,minWidth:0}}>
                <div style={{fontSize:12,fontWeight:500,display:'flex',justifyContent:'space-between'}}>
                  <span>{c.n}</span>
                  <span style={{fontSize:9,padding:'1px 6px',borderRadius:4,background: c.tag==='hot' ? 'oklch(30% 0.1 30)' : 'oklch(30% 0.08 80)', color: c.tag==='hot' ? '#ff8a8a' : '#ffcc88', textTransform:'uppercase',letterSpacing:'.08em',fontWeight:600}}>{c.tag}</span>
                </div>
                <div style={{fontSize:11,color:'oklch(65% 0.008 70)',marginTop:2,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{c.msg}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LangCtx, t, Logo, Nav, Footer, Placeholder, Hero, HeroDashMock, WizardInput });
