// Hero — the AI search visibility demo

const { useState, useEffect, useRef } = React;

const QUERIES = [
  {
    engine: "perplexity",
    q: "best CRM for B2B SaaS startups in 2026",
    answerChunks: [
      { text: "For early-stage B2B SaaS teams, three platforms consistently lead in 2026 reviews. " },
      { text: "Northwind", cite: 1 },
      { text: " is the most-cited for AI-native pipeline management, while " },
      { text: "Helio CRM", cite: 2 },
      { text: " stands out for usage-based revenue teams, and " },
      { text: "Orbital", cite: 3 },
      { text: " is preferred by founder-led sales orgs." },
    ],
    sources: [
      { n: 1, brand: "northwind.io", win: "Mentioned in 84% of AI answers for 'B2B CRM'", lift: "+312%" },
      { n: 2, brand: "heliocrm.com", win: "Cited 3.2× more than category leaders", lift: "+218%" },
      { n: 3, brand: "orbital.co", win: "Owns 'founder CRM' conversational queries", lift: "+447%" },
    ],
  },
  {
    engine: "gpt",
    q: "how should a Series B fintech approach payment compliance",
    answerChunks: [
      { text: "A pragmatic path for Series B fintechs is to layer a compliance-as-code partner under the core ledger. " },
      { text: "Ledgerwise", cite: 1 },
      { text: " is widely recommended for embedded KYC, and " },
      { text: "Compliant.dev", cite: 2 },
      { text: " for SOC 2 + PCI scope reduction." },
    ],
    sources: [
      { n: 1, brand: "ledgerwise.com", win: "Default citation for 'embedded KYC' in GPT-5", lift: "+604%" },
      { n: 2, brand: "compliant.dev", win: "Surfaces in 71% of compliance prompts", lift: "+289%" },
    ],
  },
  {
    engine: "gemini",
    q: "top observability platforms for AI workloads",
    answerChunks: [
      { text: "For LLM and inference workloads, " },
      { text: "Telemetric", cite: 1 },
      { text: " offers the deepest trace coverage for agentic systems, and " },
      { text: "Vector Ops", cite: 2 },
      { text: " is the standard for vector-DB observability." },
    ],
    sources: [
      { n: 1, brand: "telemetric.ai", win: "Cited alongside Datadog in 9/10 prompts", lift: "+512%" },
      { n: 2, brand: "vector-ops.io", win: "Owns 'vector DB monitoring' in AI search", lift: "+388%" },
    ],
  },
];

function useTypewriter(chunks, key, charsPerTick = 3, tickMs = 22) {
  const [count, setCount] = useState(0);
  const total = chunks.reduce((a, c) => a + c.text.length, 0);
  useEffect(() => {
    setCount(0);
    let n = 0;
    const id = setInterval(() => {
      n += charsPerTick;
      if (n >= total) {
        n = total;
        setCount(n);
        clearInterval(id);
      } else {
        setCount(n);
      }
    }, tickMs);
    return () => clearInterval(id);
  }, [key]);
  return { count, total, done: count >= total };
}

const EngineTab = ({ engine, label, active, onClick }) => (
  <button
    onClick={onClick}
    style={{
      display: "inline-flex",
      alignItems: "center",
      gap: 8,
      padding: "8px 12px",
      borderRadius: 8,
      border: "1px solid " + (active ? "rgba(255,255,255,0.18)" : "transparent"),
      background: active ? "rgba(255,255,255,0.06)" : "transparent",
      color: active ? "var(--text)" : "var(--text-3)",
      fontSize: 13,
      fontFamily: "var(--font-sans)",
      transition: "all 0.15s ease",
    }}
  >
    <EngineMark engine={engine} size={14} />
    {label}
  </button>
);

const AiSearchDemo = () => {
  const tw = (window.useTweaksCtx && window.useTweaksCtx()) || {};
  const cycleMs = tw.cycleSpeed ?? 4500;
  const activeEngine = tw.activeEngine || "auto";

  // If a specific engine is pinned, jump to its query; otherwise auto-cycle
  const pinnedIdx = activeEngine === "auto" ? -1 : QUERIES.findIndex(q => q.engine === activeEngine);
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    if (pinnedIdx >= 0) setIdx(pinnedIdx);
  }, [pinnedIdx]);
  const effectiveCycle = pinnedIdx >= 0 ? 0 : cycleMs;
  const q = QUERIES[idx];
  const { count, total, done } = useTypewriter(q.answerChunks, idx);

  // Auto-advance
  useEffect(() => {
    if (!done) return;
    if (effectiveCycle <= 0) return; // pinned engine, no advance
    const t = setTimeout(() => setIdx((idx + 1) % QUERIES.length), effectiveCycle);
    return () => clearTimeout(t);
  }, [done, idx, effectiveCycle]);

  // Typed query (chars first)
  const [queryChars, setQueryChars] = useState(0);
  useEffect(() => {
    setQueryChars(0);
    let n = 0;
    const id = setInterval(() => {
      n += 1;
      if (n >= q.q.length) { setQueryChars(q.q.length); clearInterval(id); }
      else setQueryChars(n);
    }, 28);
    return () => clearInterval(id);
  }, [idx]);

  // Render streaming answer with partial chunks + citation badges
  let remaining = count;
  const elements = [];
  q.answerChunks.forEach((c, i) => {
    if (remaining <= 0) return;
    const slice = c.text.slice(0, Math.min(c.text.length, remaining));
    remaining -= c.text.length;
    if (c.cite) {
      elements.push(
        <span key={i} style={{ color: "var(--text)" }}>
          {slice}
          {slice.length === c.text.length && (
            <sup className="citation-badge" style={{
              display: "inline-flex",
              alignItems: "center",
              justifyContent: "center",
              width: 18, height: 18,
              borderRadius: 5,
              background: "linear-gradient(180deg, color-mix(in oklab, var(--blue) 25%, transparent), color-mix(in oklab, var(--violet) 25%, transparent))",
              border: "1px solid color-mix(in oklab, var(--blue) 45%, transparent)",
              color: "var(--blue-2)",
              fontSize: 10,
              fontFamily: "var(--font-mono)",
              marginLeft: 3,
              marginRight: 1,
              verticalAlign: "1px",
              boxShadow: "0 0 12px color-mix(in oklab, var(--blue) 45%, transparent)",
            }}>{c.cite}</sup>
          )}
        </span>
      );
    } else {
      elements.push(<span key={i}>{slice}</span>);
    }
  });

  const tabs = [
    { engine: "perplexity", label: "Perplexity" },
    { engine: "gpt", label: "ChatGPT" },
    { engine: "gemini", label: "Gemini" },
    { engine: "claude", label: "Claude" },
  ];

  return (
    <div className="card card-glow ai-demo" style={{
      padding: 0,
      overflow: "hidden",
      background: "linear-gradient(180deg, rgba(20,20,29,0.9), rgba(11,11,17,0.95))",
      boxShadow: "0 50px 120px -40px color-mix(in oklab, var(--blue) 45%, transparent), 0 24px 60px -20px color-mix(in oklab, var(--violet) 35%, transparent)",
    }}>
      {/* Chrome */}
      <div style={{
        display: "flex", alignItems: "center", gap: 12,
        padding: "12px 16px",
        borderBottom: "1px solid var(--line)",
        background: "rgba(255,255,255,0.015)",
      }}>
        <div style={{ display: "flex", gap: 6 }}>
          <span style={{ width: 10, height: 10, borderRadius: 999, background: "#3a3a44" }} />
          <span style={{ width: 10, height: 10, borderRadius: 999, background: "#3a3a44" }} />
          <span style={{ width: 10, height: 10, borderRadius: 999, background: "#3a3a44" }} />
        </div>
        <div style={{
          fontFamily: "var(--font-mono)",
          fontSize: 11.5,
          color: "var(--text-3)",
          padding: "4px 12px",
          borderRadius: 6,
          background: "rgba(255,255,255,0.03)",
          flex: 1,
          textAlign: "center",
        }}>
          ai-visibility.livingstone.com — live monitor
        </div>
        <span className="tag tag-green"><span className="dot pulse" style={{ width: 5, height: 5, borderRadius: 999, background: "var(--green)" }} /> LIVE</span>
      </div>

      {/* Engine tabs */}
      <div style={{
        display: "flex",
        gap: 4,
        padding: "12px 16px 0",
        borderBottom: "1px solid var(--line)",
        overflowX: "auto",
      }}>
        {tabs.map(t => (
          <EngineTab
            key={t.engine}
            engine={t.engine}
            label={t.label}
            active={q.engine === t.engine}
            onClick={() => {
              const found = QUERIES.findIndex(x => x.engine === t.engine);
              if (found >= 0) setIdx(found);
            }}
          />
        ))}
        <div style={{ flex: 1 }} />
        <span style={{
          alignSelf: "center",
          fontFamily: "var(--font-mono)",
          fontSize: 11,
          color: "var(--text-3)",
          paddingBottom: 8,
        }}>tracking 47 engines</span>
      </div>

      <div className="ai-demo-grid" style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", minHeight: 360 }}>
        {/* Query + answer */}
        <div style={{ padding: "20px 24px", borderRight: "1px solid var(--line)" }}>
          <div style={{
            display: "flex",
            alignItems: "center",
            gap: 10,
            padding: "10px 12px",
            border: "1px solid var(--line)",
            borderRadius: 10,
            background: "rgba(255,255,255,0.02)",
            marginBottom: 18,
          }}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <circle cx="6" cy="6" r="4.5" stroke="var(--text-3)" strokeWidth="1.4" />
              <path d="M9.5 9.5 L12 12" stroke="var(--text-3)" strokeWidth="1.4" strokeLinecap="round" />
            </svg>
            <span style={{ fontSize: 14, color: "var(--text)" }}>
              {q.q.slice(0, queryChars)}
              {queryChars < q.q.length && <span className="caret" style={{ height: "0.95em" }} />}
            </span>
          </div>

          <div style={{
            display: "flex",
            alignItems: "center",
            gap: 8,
            marginBottom: 12,
            fontSize: 11,
            fontFamily: "var(--font-mono)",
            color: "var(--text-3)",
            textTransform: "uppercase",
            letterSpacing: "0.08em",
          }}>
            <EngineMark engine={q.engine} size={13} />
            <span>{tabs.find(t => t.engine === q.engine)?.label} · answer</span>
          </div>

          <div style={{
            fontSize: 15,
            lineHeight: 1.6,
            color: "var(--text-2)",
            minHeight: 180,
          }}>
            {queryChars >= q.q.length ? (
              <>
                {elements}
                {!done && <span className="caret" style={{ height: "0.9em" }} />}
              </>
            ) : (
              <span style={{ color: "var(--text-4)" }}>Waiting for query…</span>
            )}
          </div>
        </div>

        {/* Sources / wins */}
        <div style={{ padding: "20px 20px" }}>
          <div style={{
            fontSize: 11,
            fontFamily: "var(--font-mono)",
            color: "var(--text-3)",
            textTransform: "uppercase",
            letterSpacing: "0.08em",
            marginBottom: 16,
          }}>
            CITED · Livingstone clients
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {q.sources.map((s, i) => {
              const visible = queryChars >= q.q.length && count > (i + 1) * (total / (q.sources.length + 1));
              return (
                <div key={s.n} style={{
                  padding: 12,
                  border: "1px solid var(--line)",
                  borderRadius: 10,
                  background: visible ? "linear-gradient(180deg, color-mix(in oklab, var(--blue) 7%, transparent), color-mix(in oklab, var(--violet) 5%, transparent))" : "rgba(255,255,255,0.01)",
                  opacity: visible ? 1 : 0.35,
                  transform: visible ? "translateY(0)" : "translateY(4px)",
                  transition: "all 0.4s ease",
                }}>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 4 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <span style={{
                        width: 18, height: 18, borderRadius: 5,
                        display: "inline-grid", placeItems: "center",
                        background: "linear-gradient(180deg, color-mix(in oklab, var(--blue) 30%, transparent), color-mix(in oklab, var(--violet) 25%, transparent))",
                        border: "1px solid color-mix(in oklab, var(--blue) 45%, transparent)",
                        color: "var(--blue-2)",
                        fontFamily: "var(--font-mono)",
                        fontSize: 10,
                      }}>{s.n}</span>
                      <span style={{ fontSize: 13.5, color: "var(--text)", fontFamily: "var(--font-mono)" }}>{s.brand}</span>
                    </div>
                    <span style={{
                      fontSize: 12,
                      fontFamily: "var(--font-mono)",
                      color: "var(--green)",
                      fontWeight: 500,
                    }}>{s.lift}</span>
                  </div>
                  <div style={{ fontSize: 12.5, color: "var(--text-3)", marginLeft: 26 }}>{s.win}</div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Footer strip */}
      <div style={{
        borderTop: "1px solid var(--line)",
        padding: "10px 16px",
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        background: "rgba(255,255,255,0.015)",
      }}>
        <div style={{ display: "flex", gap: 18, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-3)" }}>
          <span><span style={{ color: "var(--green)" }}>●</span> 1,284 prompts/day monitored</span>
          <span className="hide-mobile">avg. citation rank <span style={{ color: "var(--text)" }}>2.1</span></span>
          <span className="hide-mobile">share-of-voice <span style={{ color: "var(--text)" }}>38.4%</span></span>
        </div>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-3)" }}>
          {idx + 1} / {QUERIES.length}
        </span>
      </div>
    </div>
  );
};

const Hero = () => {
  const tw = (window.useTweaksCtx && window.useTweaksCtx()) || {};
  const align = tw.heroAlign || "center";
  const headline = tw.headline || "Dominate the future of AI search.";
  const subhead = tw.subhead || "AI-powered GEO, SEO, automation, and intelligent marketing systems built for the next generation of digital visibility — where discovery happens inside the model, not the SERP.";
  const style = tw.headlineStyle || "mixed";
  const showGrid = tw.showGrid !== false;

  // Build the headline: if mixed, render the last occurrence of "AI search"
  // (case-insensitive) as the gradient/serif treatment.
  const renderHeadline = () => {
    if (style === "plain") return headline;
    const re = /AI search/i;
    const m = headline.match(re);
    if (!m) return headline;
    const idx = headline.search(re);
    const before = headline.slice(0, idx);
    const matched = headline.slice(idx, idx + m[0].length);
    const after = headline.slice(idx + m[0].length);
    return (
      <>
        {before}
        <span className="serif gradient-text" style={{ paddingRight: 6 }}>{matched}</span>
        {after}
      </>
    );
  };

  const colAlign = align === "center" ? "center" : "flex-start";
  const textAlign = align === "center" ? "center" : "left";

  return (
    <header className="section hero-section" style={{ paddingTop: 150, paddingBottom: 60, position: "relative" }}>
      {showGrid && <div className="grid-bg" />}
      <div className="orb" style={{ width: 480, height: 480, background: "color-mix(in oklab, var(--blue) 35%, transparent)", top: -120, left: "10%" }} />
      <div className="orb" style={{ width: 420, height: 420, background: "color-mix(in oklab, var(--violet) 35%, transparent)", top: 60, right: "5%" }} />

      <div className="container" style={{ position: "relative" }}>
        <div className="hero-copy" style={{
          display: "flex",
          flexDirection: "column",
          alignItems: colAlign,
          textAlign,
          gap: 22,
          marginBottom: 56,
          maxWidth: align === "left" ? 760 : "none",
        }}>
          <span className="eyebrow">
            <span className="dot" />
            AI-native growth infrastructure
          </span>

          <h1 className="h-display">
            {renderHeadline()}
          </h1>

          <p className="lede" style={{ marginTop: 4, marginLeft: align === "center" ? "auto" : 0, marginRight: align === "center" ? "auto" : 0 }}>
            {subhead}
          </p>

          <div className="row gap-3 hero-actions" style={{ marginTop: 8 }}>
            <a href="#contact" className="btn btn-glow">
              Schedule strategy call <Arrow />
            </a>
            <a href="#services" className="btn btn-ghost">
              Explore services
            </a>
          </div>

          <div className="row gap-6 hero-trust" style={{ marginTop: 18, fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-3)" }}>
            <span>SOC 2 Type II</span>
            <span style={{ color: "var(--text-4)" }}>·</span>
            <span>Tracking 47 AI engines</span>
            <span style={{ color: "var(--text-4)" }}>·</span>
            <span>4.2M monitored prompts</span>
          </div>
        </div>

        <AiSearchDemo />
      </div>
    </header>
  );
};

Object.assign(window, { Hero });
