const { useState, useEffect, useRef } = React;

/* ---------- typing helper ---------- */
function useTyping(text, speed = 22, start = true, restart = 0) {
  const [out, setOut] = useState("");
  useEffect(() => {
    if (!start) return;
    setOut("");
    let i = 0;
    const id = setInterval(() => {
      i++;
      setOut(text.slice(0, i));
      if (i >= text.length) clearInterval(id);
    }, speed);
    return () => clearInterval(id);
  }, [text, start, speed, restart]);
  return out;
}

/* ---------- live sparkline ---------- */
function Spark() {
  const [pts, setPts] = useState(() => Array.from({length: 24}, () => 10 + Math.random()*16));
  useEffect(() => {
    const id = setInterval(() => {
      setPts(p => [...p.slice(1), 8 + Math.random()*20]);
    }, 700);
    return () => clearInterval(id);
  }, []);
  const w = 120, h = 28;
  const step = w / (pts.length - 1);
  const d = pts.map((y, i) => `${i===0?'M':'L'}${(i*step).toFixed(1)},${(h - y).toFixed(1)}`).join(' ');
  const area = `${d} L${w},${h} L0,${h} Z`;
  return (
    <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} style={{display:'block'}}>
      <defs>
        <linearGradient id="sparkFill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.4"/>
          <stop offset="100%" stopColor="var(--accent)" stopOpacity="0"/>
        </linearGradient>
      </defs>
      <path d={area} fill="url(#sparkFill)"/>
      <path d={d} fill="none" stroke="var(--accent)" strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round"/>
    </svg>
  );
}

/* ---------- Workspace UI (hero) ---------- */
function WorkspaceUI({ copy }) {
  const w = copy.workspace;

  // cycle through email drafts
  const drafts = [
    { to: "marc.lehmann@kunde.ch", subject: "Re: Angebot Q3 Roadmap", body: "Hallo Marc,\n\ndanke für deine Rückmeldung. Anbei die aktualisierte Roadmap mit den Meilensteinen für Q3. Lass uns Mittwoch 14:30 kurz syncen — ich blocke direkt im Kalender." },
    { to: "team@baeumlin.ch", subject: "Re: Onboarding-Workshop nächste Woche", body: "Hi zusammen,\n\nder Workshop ist auf Dienstag 09:00 fixiert. Die Unterlagen liegen im geteilten Drive — bitte vorab durchgehen. Bei Fragen meldet euch direkt." },
    { to: "finance@kunde.ch", subject: "Re: Rechnung INV-2026-0412", body: "Hallo,\n\ndie Rechnung wurde heute Morgen beglichen — Referenz im Anhang. Bei weiteren Fragen stehe ich gerne zur Verfügung." }
  ];

  const [draftIdx, setDraftIdx] = useState(0);
  const [tick, setTick] = useState(0);
  const current = drafts[draftIdx];
  const body = useTyping(current.body, 14, true, draftIdx);

  // advance to next draft after the body finishes + a pause
  useEffect(() => {
    const totalMs = current.body.length * 14 + 2400;
    const id = setTimeout(() => {
      setDraftIdx(i => (i + 1) % drafts.length);
      setTick(t => t + 1);
    }, totalMs);
    return () => clearTimeout(id);
  }, [draftIdx]);

  const [activeSidebar, setActiveSidebar] = useState(1); // Drafts

  return (
    <div className="ws-shell">
      {/* chrome */}
      <div className="ws-chrome">
        <div className="ws-dots">
          <span style={{background:'#ff5f57'}}></span>
          <span style={{background:'#ffbd2e'}}></span>
          <span style={{background:'#28c941'}}></span>
        </div>
        <div className="ws-title mono">{w.title}</div>
        <div className="ws-tools mono">
          <span className="pulse-dot"></span> live
        </div>
      </div>

      <div className="ws-body">
        {/* sidebar */}
        <aside className="ws-side">
          <div className="ws-side-head mono">WORKSPACE</div>
          <ul>
            {w.sidebar.map((s, i) => (
              <li key={s}
                  className={activeSidebar === i ? 'active' : ''}
                  onMouseEnter={() => setActiveSidebar(i)}>
                <span className="ws-side-icon">
                  <SidebarIcon i={i}/>
                </span>
                {s}
                {i === 0 && <span className="ws-badge">12</span>}
              </li>
            ))}
          </ul>
          <div className="ws-side-foot">
            <div className="ws-avatar"></div>
            <div>
              <div style={{fontSize:12, color:'var(--text)'}}>Lara K.</div>
              <div style={{fontSize:10, color:'var(--text-3)'}} className="mono">admin</div>
            </div>
          </div>
        </aside>

        {/* main */}
        <main className="ws-main">
          <div className="ws-card ws-draft">
            <div className="ws-card-head">
              <div className="ws-card-eyebrow mono">
                <span className="dot"></span>{w.draft.toUpperCase()}
              </div>
              <div className="ws-card-meta mono">AI · GPT-4 · just now</div>
            </div>
            <div className="ws-mail-row">
              <span className="ws-label mono">TO</span>
              <span className="ws-val">{current.to}</span>
            </div>
            <div className="ws-mail-row">
              <span className="ws-label mono">SUBJ</span>
              <span className="ws-val" style={{color:'var(--text)'}}>{current.subject}</span>
            </div>
            <pre className="ws-body-text">{body}<span className="caret">▍</span></pre>
            <div className="ws-actions">
              <button className="ws-pill primary">Approve & send ↗</button>
              <button className="ws-pill">Regenerate</button>
              <button className="ws-pill">Edit</button>
              <div style={{flex:1}}></div>
              <span className="mono" style={{fontSize:11, color:'var(--text-3)'}}>{w.draftSub}</span>
            </div>
          </div>

          <div className="ws-grid">
            <div className="ws-card ws-intel">
              <div className="ws-card-head">
                <div className="ws-card-eyebrow mono"><span className="dot"></span>{w.intel.toUpperCase()}</div>
                <div className="mono" style={{fontSize:11, color:'var(--accent)'}}>{w.eff}</div>
              </div>
              <div style={{display:'flex', alignItems:'baseline', gap:8, marginTop:8}}>
                <div className="ws-bignum serif">{w.hours}</div>
                <div className="mono" style={{fontSize:11, color:'var(--text-3)'}}>{w.saved}</div>
              </div>
              <div style={{marginTop:14}}><Spark/></div>
            </div>

            <div className="ws-card ws-auto">
              <div className="ws-card-head">
                <div className="ws-card-eyebrow mono"><span className="dot"></span>{w.auto.toUpperCase()}</div>
              </div>
              <ul className="ws-auto-list">
                {w.autoItems.map((item, i) => (
                  <li key={item}>
                    <Check/> {item}
                  </li>
                ))}
              </ul>
              <div className="ws-found">
                <div>
                  <div className="mono" style={{fontSize:10, color:'var(--accent)', letterSpacing:'0.12em'}}>● {w.found.toUpperCase()}</div>
                  <div style={{fontSize:13, color:'var(--text)', marginTop:4}}>{w.foundDetail}</div>
                </div>
                <button className="ws-pill">Review →</button>
              </div>
            </div>
          </div>
        </main>
      </div>

      <style>{`
        .ws-shell {
          width: 100%;
          background: linear-gradient(180deg, #0e1014, #0a0b0e);
          border: 1px solid var(--line);
          border-radius: 18px;
          overflow: hidden;
          box-shadow:
            0 1px 0 rgba(255,255,255,0.04) inset,
            0 40px 120px -20px rgba(0,0,0,0.6),
            0 0 0 1px rgba(255,255,255,0.02);
          position: relative;
        }
        .ws-chrome {
          display: flex; align-items: center; gap: 16px;
          padding: 12px 16px;
          border-bottom: 1px solid var(--line);
          background: rgba(255,255,255,0.015);
        }
        .ws-dots { display: flex; gap: 6px; }
        .ws-dots span { width: 11px; height: 11px; border-radius: 50%; }
        .ws-title { flex: 1; font-size: 11px; color: var(--text-3); text-align: center; letter-spacing: 0.04em; }
        .ws-tools { font-size: 11px; color: var(--text-3); display: flex; align-items: center; gap: 6px; }
        .pulse-dot { width: 6px; height: 6px; border-radius: 50%; background: oklch(0.85 0.15 145); box-shadow: 0 0 8px oklch(0.85 0.15 145); animation: pulse 1.8s ease-in-out infinite; }

        .ws-body { display: grid; grid-template-columns: 200px 1fr; min-height: 460px; }
        @media (max-width: 720px) { .ws-body { grid-template-columns: 1fr; } .ws-side { display: none; } }

        .ws-side { border-right: 1px solid var(--line); padding: 18px 14px; display: flex; flex-direction: column; gap: 16px; background: rgba(255,255,255,0.012); }
        .ws-side-head { font-size: 10px; color: var(--text-3); letter-spacing: 0.16em; padding: 0 8px; }
        .ws-side ul { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 2px; }
        .ws-side li {
          display: flex; align-items: center; gap: 10px;
          padding: 8px 10px;
          border-radius: 8px;
          font-size: 13px;
          color: var(--text-2);
          cursor: pointer;
          transition: background 0.2s, color 0.2s;
          position: relative;
        }
        .ws-side li:hover { background: rgba(255,255,255,0.03); color: var(--text); }
        .ws-side li.active { background: rgba(255,255,255,0.05); color: var(--text); }
        .ws-side li.active::before { content: ""; position: absolute; left: 0; top: 8px; bottom: 8px; width: 2px; background: var(--accent); border-radius: 2px; }
        .ws-side-icon { width: 16px; height: 16px; display: inline-flex; align-items: center; justify-content: center; color: var(--text-3); }
        .ws-side li.active .ws-side-icon { color: var(--accent); }
        .ws-badge { margin-left: auto; font-family: var(--mono); font-size: 10px; color: var(--text-3); background: rgba(255,255,255,0.05); padding: 2px 6px; border-radius: 999px; }

        .ws-side-foot { margin-top: auto; display: flex; align-items: center; gap: 10px; padding: 10px; border-top: 1px solid var(--line); }
        .ws-avatar { width: 28px; height: 28px; border-radius: 50%; background: linear-gradient(135deg, oklch(0.7 0.12 280), oklch(0.65 0.14 200)); }

        .ws-main { padding: 22px; display: flex; flex-direction: column; gap: 16px; min-width: 0; }

        .ws-card {
          background: rgba(255,255,255,0.02);
          border: 1px solid var(--line);
          border-radius: 12px;
          padding: 18px;
          position: relative;
        }
        .ws-card-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
        .ws-card-eyebrow { font-size: 10px; color: var(--text-3); letter-spacing: 0.16em; display: flex; align-items: center; gap: 6px; }
        .ws-card-eyebrow .dot { width: 6px; height: 6px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 8px var(--accent); }
        .ws-card-meta { font-size: 10px; color: var(--text-3); }

        .ws-draft { background: linear-gradient(180deg, rgba(255,255,255,0.025), rgba(255,255,255,0.005)); }
        .ws-mail-row { display: flex; gap: 12px; font-size: 12px; padding: 8px 0; border-bottom: 1px dashed rgba(255,255,255,0.06); }
        .ws-mail-row:first-of-type { margin-top: 12px; }
        .ws-label { color: var(--text-3); width: 38px; }
        .ws-val { color: var(--text-2); }
        .ws-body-text {
          margin: 14px 0 16px;
          font-family: var(--sans);
          font-size: 13px;
          color: var(--text);
          line-height: 1.6;
          white-space: pre-wrap;
          min-height: 96px;
        }
        .caret { display: inline-block; width: 8px; color: var(--accent); animation: blink 1s steps(2) infinite; transform: translateY(-1px); }
        .ws-actions { display: flex; gap: 8px; align-items: center; }
        .ws-pill {
          font-family: var(--sans);
          font-size: 11px;
          padding: 7px 12px;
          background: rgba(255,255,255,0.04);
          border: 1px solid var(--line);
          color: var(--text-2);
          border-radius: 999px;
          cursor: pointer;
          transition: all 0.2s;
        }
        .ws-pill:hover { color: var(--text); border-color: var(--line-2); background: rgba(255,255,255,0.07); }
        .ws-pill.primary { background: var(--text); color: #0a0a0a; border-color: var(--text); }
        .ws-pill.primary:hover { background: #fff; }

        .ws-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
        @media (max-width: 600px) { .ws-grid { grid-template-columns: 1fr; } }

        .ws-bignum { font-size: 36px; line-height: 1; letter-spacing: -0.03em; }
        .ws-auto-list { list-style: none; padding: 0; margin: 14px 0 0; display: flex; flex-direction: column; gap: 8px; font-size: 12px; color: var(--text-2); }
        .ws-auto-list li { display: flex; align-items: center; gap: 8px; }
        .ws-found {
          margin-top: 14px;
          padding: 12px;
          background: rgba(255,255,255,0.025);
          border: 1px dashed var(--accent-line);
          border-radius: 8px;
          display: flex; align-items: center; justify-content: space-between; gap: 10px;
        }
      `}</style>
    </div>
  );
}

function Check() {
  return (
    <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
      <circle cx="7" cy="7" r="6" stroke="var(--accent-line)" strokeWidth="1"/>
      <path d="M4 7.5l2 2 4-5" stroke="var(--accent)" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

function SidebarIcon({ i }) {
  const paths = [
    "M3 5h10v6H3z M3 5l5 4 5-4", // inbox
    "M4 3h6l3 3v7H4z M10 3v3h3",  // drafts
    "M3 8h10 M3 4h10 M3 12h6",    // workflows
    "M3 4h10v8H3z M3 8h10",        // knowledge
    "M3 12V4 M3 12h10 M6 12V8 M9 12V6 M12 12V9", // analyzer (bars)
    "M8 5v6 M5 8h6 M8 2v2 M8 12v2 M2 8h2 M12 8h2", // settings
  ];
  return (
    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round">
      <path d={paths[i]}/>
    </svg>
  );
}

/* ---------- Hero ---------- */
function Hero({ copy }) {
  const h = copy.hero;
  return (
    <section className="hero" id="top">
      {/* subtle ambient — no rainbow orbs */}
      <div className="hero-amb"></div>
      <div className="grid-bg"></div>

      <div className="container hero-inner">
        <div className="hero-pill mono">
          <span className="hero-pill-dot"></span>{h.pill}
        </div>

        <h1 className="hero-h1">
          <span className="serif">{h.h1_1}</span>{' '}
          <span className="serif italic outlined">{h.h1_2}</span>
          <br/>
          <span className="serif">{h.h1_3}</span>
        </h1>

        <p className="hero-sub">{h.sub}</p>

        <div className="hero-ctas">
          <a href="#cta" className="btn btn-primary">{h.cta1} <span className="arrow">↗</span></a>
          <a href="#how" className="btn btn-ghost">{h.cta2}</a>
        </div>

        <div className="hero-chips">
          {h.chips.map((c, i) => (
            <div className="hero-chip mono" key={c}>
              <Dot/> {c}
            </div>
          ))}
        </div>

        <div className="hero-workspace reveal in">
          {/* floating callout: hours saved (top-left) */}
          <div className="hero-float hero-float-tl">
            <div className="hero-float-row">
              <div className="hero-float-icon">
                <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M3 13V9 M7 13V5 M11 13V7 M15 13V3"/>
                </svg>
              </div>
              <div className="hero-float-label">{copy.workspace.saved}</div>
            </div>
            <div className="hero-float-big serif">{copy.workspace.hours}</div>
            <div className="hero-float-trend mono"><span style={{color:'oklch(0.85 0.15 145)'}}>▲</span> +18.4% vs. letzte Woche</div>
          </div>

          {/* floating callout: automation found (bottom-right) */}
          <div className="hero-float hero-float-br">
            <div className="hero-float-row">
              <span className="hero-float-pulse"></span>
              <div className="hero-float-label">{copy.workspace.found}</div>
            </div>
            <div className="hero-float-detail">{copy.workspace.foundDetail}</div>
            <div className="hero-float-meta mono">92×/Monat · ROI 88/100 →</div>
          </div>

          <WorkspaceUI copy={copy}/>
        </div>
      </div>

      <style>{`
        .hero { padding-top: 140px; padding-bottom: 100px; overflow: hidden; }
        .grid-bg {
          position: absolute; inset: 0; pointer-events: none;
          background-image:
            linear-gradient(rgba(255,255,255,0.025) 1px, transparent 1px),
            linear-gradient(90deg, rgba(255,255,255,0.025) 1px, transparent 1px);
          background-size: 64px 64px;
          mask-image: radial-gradient(ellipse 80% 60% at 50% 30%, #000 30%, transparent 75%);
          -webkit-mask-image: radial-gradient(ellipse 80% 60% at 50% 30%, #000 30%, transparent 75%);
        }
        .hero-inner { position: relative; z-index: 2; text-align: center; }
        .hero-pill {
          display: inline-flex; align-items: center; gap: 8px;
          padding: 6px 14px;
          border: 1px solid var(--line-2);
          background: rgba(255,255,255,0.02);
          border-radius: 999px;
          font-size: 11px;
          color: var(--text-2);
          letter-spacing: 0.04em;
        }
        .hero-pill-dot { width:6px;height:6px;border-radius:50%;background: var(--accent); box-shadow: 0 0 10px var(--accent); animation: pulse 2s ease-in-out infinite; }
        .hero-h1 {
          font-size: clamp(40px, 5.8vw, 88px);
          line-height: 1.06;
          margin: 28px auto 0;
          letter-spacing: -0.025em;
          text-wrap: balance;
        }
        .hero-h1 .italic { font-style: italic; }
        .hero-h1 .outlined {
          color: transparent;
          -webkit-text-stroke: 1px var(--text-2);
          background: linear-gradient(180deg, var(--text-2), var(--text-3));
          -webkit-background-clip: text;
          background-clip: text;
        }
        .hero-sub {
          max-width: 60ch;
          margin: 24px auto 0;
          color: var(--text-2);
          font-size: 18px;
          line-height: 1.55;
          text-wrap: pretty;
        }
        .hero-ctas { display: flex; gap: 12px; justify-content: center; margin-top: 32px; }
        .hero-chips { display: flex; gap: 10px; justify-content: center; flex-wrap: wrap; margin-top: 28px; }
        .hero-chip {
          display: inline-flex; align-items: center; gap: 8px;
          padding: 7px 12px;
          background: rgba(255,255,255,0.02);
          border: 1px solid var(--line);
          border-radius: 999px;
          font-size: 11px;
          color: var(--text-2);
        }
        .hero-workspace {
          margin-top: 72px;
          max-width: 1080px;
          margin-left: auto; margin-right: auto;
          position: relative;
        }
        .hero-workspace::before {
          content: "";
          position: absolute;
          inset: -80px -40px -40px -40px;
          background: radial-gradient(ellipse 60% 50% at 50% 40%, rgba(255,255,255,0.04), transparent 70%);
          pointer-events: none;
          z-index: -1;
        }
        .hero-amb {
          position: absolute;
          inset: 0;
          pointer-events: none;
          background: radial-gradient(ellipse 50% 40% at 50% 30%, rgba(255,255,255,0.025), transparent 70%);
        }

        /* floating callouts */
        .hero-float {
          position: absolute;
          z-index: 5;
          background: linear-gradient(180deg, rgba(20,22,28,0.95), rgba(14,16,20,0.95));
          border: 1px solid var(--line-2);
          border-radius: 14px;
          padding: 16px 18px;
          backdrop-filter: blur(20px);
          box-shadow:
            0 1px 0 rgba(255,255,255,0.05) inset,
            0 24px 60px -10px rgba(0,0,0,0.7),
            0 0 0 1px rgba(255,255,255,0.02);
          text-align: left;
          min-width: 220px;
          animation: floatIn 1.2s cubic-bezier(0.2,0.7,0.2,1) both;
        }
        .hero-float-tl { top: -28px; left: -24px; animation-delay: 0.4s; }
        .hero-float-br { bottom: -36px; right: -24px; animation-delay: 0.6s; }
        @keyframes floatIn {
          from { opacity: 0; transform: translateY(20px) scale(0.94); }
          to { opacity: 1; transform: none; }
        }
        @media (max-width: 720px) {
          .hero-float-tl { top: -12px; left: 8px; }
          .hero-float-br { bottom: -16px; right: 8px; }
          .hero-float { min-width: auto; padding: 12px 14px; }
        }
        .hero-float-row { display: flex; align-items: center; gap: 10px; }
        .hero-float-icon { width: 22px; height: 22px; border-radius: 6px; border: 1px solid var(--accent-line); background: var(--accent-soft); display: flex; align-items: center; justify-content: center; color: var(--accent); }
        .hero-float-label { font-size: 12px; color: var(--text-2); }
        .hero-float-big { font-size: 36px; line-height: 1; letter-spacing: -0.03em; margin-top: 8px; color: var(--text); }
        .hero-float-detail { font-size: 16px; line-height: 1.25; color: var(--text); margin-top: 6px; }
        .hero-float-meta { font-size: 10px; color: var(--text-3); margin-top: 8px; letter-spacing: 0.04em; }
        .hero-float-trend { font-size: 10px; color: var(--text-3); margin-top: 6px; letter-spacing: 0.04em; }
        .hero-float-pulse { width: 8px; height: 8px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 12px var(--accent); animation: pulse 1.8s ease-in-out infinite; }
      `}</style>
    </section>
  );
}

function Dot() {
  return <span style={{width:5, height:5, borderRadius:'50%', background:'var(--accent)', display:'inline-block'}}/>;
}

Object.assign(window, { Hero, WorkspaceUI, Dot, Check, useTyping, Spark, SidebarIcon });
