/* global React, ReactDOM, Logo, I, VisCite, VisSource, VisHonest */
const { useState, useEffect, useRef, useCallback } = React;

/* ============================================
   Ask box — input + chips, no answer panel
   ============================================ */
function AskBox({ chips }) {
  const [value, setValue] = useState("");
  const [animPlaceholder, setAnimPlaceholder] = useState("");
  const [focused, setFocused] = useState(false);
  const inputRef = useRef(null);

  // Animated typing placeholder — cycles through example questions
  useEffect(() => {
    if (focused || value) return;
    const phrases = chips.map(c => c.q);
    let phraseIdx = 0;
    let charIdx = 0;
    let mode = 'typing';
    let timer;

    const tick = () => {
      const phrase = phrases[phraseIdx];
      if (mode === 'typing') {
        charIdx++;
        setAnimPlaceholder(phrase.slice(0, charIdx));
        if (charIdx >= phrase.length) {
          mode = 'holding';
          timer = setTimeout(tick, 2400);
          return;
        }
        timer = setTimeout(tick, 65 + Math.random() * 50);
      } else if (mode === 'holding') {
        mode = 'deleting';
        timer = setTimeout(tick, 120);
      } else {
        charIdx -= 1;
        if (charIdx < 0) charIdx = 0;
        setAnimPlaceholder(phrase.slice(0, charIdx));
        if (charIdx === 0) {
          mode = 'typing';
          phraseIdx = (phraseIdx + 1) % phrases.length;
          timer = setTimeout(tick, 600);
          return;
        }
        timer = setTimeout(tick, 32);
      }
    };
    timer = setTimeout(tick, 400);
    return () => clearTimeout(timer);
  }, [focused, value, chips]);

  const handleChip = (chip) => {
    setValue(chip.q);
    inputRef.current && inputRef.current.focus();
  };

  const onKey = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
    }
  };

  return (
    <>
      <div className="ask">
        <div className="ask-row">
          <input
            ref={inputRef}
            className="ask-input"
            placeholder={animPlaceholder || "Ask anything…"}
            value={value}
            onChange={(e) => setValue(e.target.value)}
            onFocus={() => setFocused(true)}
            onBlur={() => setFocused(false)}
            onKeyDown={onKey}
          />
          <button
            className="ask-btn"
            disabled={!value.trim()}
            aria-label="Ask"
          >
            {I.arrow}
          </button>
        </div>
      </div>

      <div className="ask-chips">
        {chips.map((c, i) => (
          <button key={i} className="chip" onClick={() => handleChip(c)}>
            {c.q}
          </button>
        ))}
      </div>
    </>
  );
}
window.AskBox = AskBox;

/* ============================================
   Nav
   ============================================ */
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="container nav-inner">
        <Logo size={22} />
        <div className="nav-links">
          <a href="#how">How it works</a>
          <a href="#who">Use cases</a>
          <a href="#pricing">Pricing</a>
        </div>
        <div className="nav-cta">
          <a href="#" className="nav-signin">Sign in</a>
          <button className="btn btn-primary btn-sm">Sign up free</button>
        </div>
      </div>
    </nav>
  );
}
window.Nav = Nav;

/* ============================================
   Hero
   ============================================ */
function Hero({ headline = "default" }) {
  const chips = window.GOSPEL_QUESTIONS.hero;

  const headlines = {
    default: <>Every <span className="accent">answer<span className="sup">[1]</span></span>, sourced.</>,
    citations: <>Citations <span className="accent">first<span className="sup">[1]</span></span>. Always.</>,
    truth: <>Your sources. Your <span className="accent">truth<span className="sup">[1]</span></span>.</>,
  };

  return (
    <section className="hero">
      <div className="hero-grad" />
      <div className="container hero-inner">
        <div className="hero-eyebrow">
          <span className="dot" />
          Now in public beta · no signup required
        </div>
        <h1>{headlines[headline] || headlines.default}</h1>
        <p className="hero-sub">
          Ask any research question. Get an answer grounded in sources you trust. Every claim cited. Nothing made up.
        </p>
        <AskBox chips={chips} />
      </div>
    </section>
  );
}
window.Hero = Hero;

/* ============================================
   Three things
   ============================================ */
function ThreeThings() {
  const cells = [
    { num: "Cited", vis: <VisCite />, h: "Cited, always.", p: "Every claim links to its source. Open the source in one click. No black boxes." },
    { num: "Sourced", vis: <VisSource />, h: "Bring your own sources.", p: "Upload your archive. Connect your journals. Add domains you trust. Gospel grounds answers in your hierarchy of truth." },
    { num: "Honest", vis: <VisHonest />, h: "It admits when it doesn't know.", p: "If the sources don't support an answer, Gospel says so. No hallucinations. No confident guesses." },
  ];
  return (
    <section className="three-things" id="how">
      <div className="container">
        <div className="section-head">
          <div>
            <span className="eyebrow">How it works</span>
            <h2 style={{ marginTop: 12 }}>Three things, every time.</h2>
          </div>
        </div>
        <div className="three-grid">
          {cells.map((c, i) => (
            <div key={i} className="three-cell">
              <div className="three-vis">{c.vis}</div>
              <div className="three-num">{c.num}</div>
              <h3 className="three-h">{c.h}</h3>
              <p className="three-p">{c.p}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}
window.ThreeThings = ThreeThings;

/* ============================================
   Who it's for
   ============================================ */
function WhoItsFor() {
  const cards = [
    { tag: "For research", h: "Researchers", p: "Cite as you write. Every claim traceable to its source." },
    { tag: "For policy", h: "Policymakers", p: "Ground analysis in your archives, not the open web." },
    { tag: "For news", h: "Journalists", p: "Verify before you publish. Sources surface in seconds." },
    { tag: "For teams", h: "Institutions", p: "Replace \"ask the librarian\" with \"ask Gospel.\"" },
  ];
  return (
    <section className="who" id="who">
      <div className="container">
        <span className="eyebrow">Use cases</span>
        <h2 className="who-h" style={{ marginTop: 12 }}>
          Built for people who can't afford to be <em>wrong</em>.
        </h2>
        <div className="who-grid">
          {cards.map((c, i) => (
            <div key={i} className="who-card">
              <span className="who-tag">{c.tag}</span>
              <h4>{c.h}</h4>
              <p>{c.p}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}
window.WhoItsFor = WhoItsFor;

/* ============================================
   Comparison
   ============================================ */
function Compare() {
  const rows = [
    ["Trained on the open web", "Grounded in sources you choose"],
    ["Confidently wrong", "Cites every claim, or admits the gap"],
    ["One source of truth", "Your hierarchy of trust"],
    ["Black box", "Open citations, full provenance"],
  ];
  return (
    <section className="compare">
      <div className="container">
        <span className="eyebrow">How it's different</span>
        <h2 className="compare-h" style={{ marginTop: 12 }}>
          The difference is the receipt.
        </h2>
        <div className="compare-table">
          <div className="compare-col-h left">Other AI chatbots</div>
          <div className="compare-col-h right">Gospel</div>
          {rows.map((r, i) => (
            <div key={i} className="compare-row">
              <div className="compare-cell left">
                <span className="compare-icon">{I.x}</span>
                <span>{r[0]}</span>
              </div>
              <div className="compare-cell right">
                <span className="compare-icon">{I.check}</span>
                <span>{r[1]}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}
window.Compare = Compare;

/* ============================================
   Retry section (second ask box)
   ============================================ */
function Retry() {
  const chips = window.GOSPEL_QUESTIONS.retry;
  return (
    <section className="retry">
      <div className="container retry-inner">
        <h2 style={{ marginTop: 0 }}>Try another question.</h2>
        <p className="retry-sub">
          Different domain, same Gospel.
        </p>
        <div style={{ width: '100%' }}>
          <AskBox chips={chips} />
        </div>
      </div>
    </section>
  );
}
window.Retry = Retry;

/* ============================================
   Pricing
   ============================================ */
function Pricing() {
  return (
    <section className="pricing" id="pricing">
      <div className="container">
        <span className="eyebrow">Pricing</span>
        <h2 className="pricing-h" style={{ marginTop: 12 }}>Simple. No fine print.</h2>
        <p className="pricing-sub">Start free. Upgrade when you want your own sources.</p>
        <div className="price-grid">
          <div className="price-card">
            <div>
              <div className="price-tier">Free</div>
              <div className="price-amount" style={{ marginTop: 16 }}>$0</div>
            </div>
            <ul className="price-features">
              <li>{I.check}<span>50 questions per month</span></li>
              <li>{I.check}<span>Public sources only</span></li>
              <li>{I.check}<span>Citations in every answer</span></li>
            </ul>
            <button className="btn btn-ghost">Start free</button>
          </div>

          <div className="price-card featured">
            <div>
              <div className="price-tier">Pro</div>
              <div className="price-amount" style={{ marginTop: 16 }}>
                $29 <span className="per">/ month</span>
              </div>
            </div>
            <ul className="price-features">
              <li>{I.check}<span>Unlimited questions</span></li>
              <li>{I.check}<span>Bring your own sources</span></li>
              <li>{I.check}<span>Save and organize answers</span></li>
              <li>{I.check}<span>Export to PDF, Word, Notion</span></li>
            </ul>
            <button className="btn btn-primary">Go Pro</button>
          </div>

          <div className="price-card">
            <div>
              <div className="price-tier">Team / Institutional</div>
              <div className="price-amount" style={{ marginTop: 16, fontSize: 32 }}>Talk to us</div>
            </div>
            <ul className="price-features">
              <li>{I.check}<span>Custom source integration</span></li>
              <li>{I.check}<span>SSO and admin controls</span></li>
              <li>{I.check}<span>On-prem deployment available</span></li>
              <li>{I.check}<span>Priority support</span></li>
            </ul>
            <button className="btn btn-ghost">Contact us</button>
          </div>
        </div>
      </div>
    </section>
  );
}
window.Pricing = Pricing;

/* ============================================
   Final CTA
   ============================================ */
function FinalCTA() {
  return (
    <section className="final-cta">
      <div className="container">
        <h2>Stop fact-checking <em>your AI</em>.</h2>
        <button className="btn btn-primary btn-lg">
          Try Gospel free
        </button>
      </div>
    </section>
  );
}
window.FinalCTA = FinalCTA;

/* ============================================
   Footer
   ============================================ */
function Footer() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-bottom">
          <Logo size={18} />
          <span><em>Every answer, sourced.</em></span>
          <span><a href="#" style={{ color: 'var(--fg-3)' }}>Privacy Policy</a></span>
        </div>
      </div>
    </footer>
  );
}
window.Footer = Footer;
