// hero.jsx — Interactive LLM terminal as the centerpiece

const SYSTEM_PROMPT = `You are the terminal interface on chetanbatra.com — Chetan Batra's personal website.

About Chetan:
- GTM Engineer at Gravitee (https://www.gravitee.io/), based in New Delhi, working US/EU hours
- 5 years of B2B sales before turning engineer: Marketing at OyeLabs, Customer Success then Enterprise Sales at Xeno (closed deals with Bestseller, Madame, SSIPL, Chumbak, Colorbar; built $500K pipeline), Enterprise Sales at Wigzo (single-handedly led retail, ₹1.2 Cr ARR closed), Chief of Staff at Togethr (scaled 0 → 15-20L MRR, built 4-person sales team, secured partnerships with Neemans, Mokobara, Clovia, Air India Express), Revenue Partner at Polynation Ventures selling Onebeat (AI inventory optimization for retailers)
- Now builds: this personal site, n8n social-media autopilot, custom Apify scrapers (LinkedIn + websites), Clay/Claygent workflows, outbound systems with Smartlead
- Stack: Clay, Claygent, Apify, n8n, Smartlead, Instantly, OpenAI, Anthropic, Cursor, Notion, HubSpot, Apollo, Make
- Specialty: finding hard-to-find buyers (traditional industries, emerging markets) that aren't in Apollo or ZoomInfo
- Email: chetanbatra2000@gmail.com · LinkedIn: linkedin.com/in/chetanbatra
- This site is a showcase of his journey + builds, not a sales pitch. He's not looking for clients right now.

Voice: playful, builder-energy, casual, lowercase-ish, occasionally irreverent. No corporate-speak. No "leveraging synergies." Talk like a slightly tired engineer who's seen too many cold-email tools. Use line breaks for readability.

Rules:
- Keep replies SHORT — 2-4 sentences usually, never more than ~80 words.
- If asked something you don't know, say so honestly ("no clue, ask him on linkedin"). Never fabricate dates, deals, or projects.
- If the user asks something off-topic (math, code, world politics), gently redirect: "i only know chetan stuff — try asking about the journey or the builds."
- Don't list every job. Pick the most relevant 1-2 things.
- It's okay to have a sense of humor. Don't be weird.`;

const SUGGESTIONS = [
  "who is chetan?",
  "what are you building?",
  "the journey, fast version",
  "what's claygent?",
  "tell me a sales war story",
  "why GTM engineer?",
];

function useTypewriter(text, speed = 18) {
  const [out, setOut] = React.useState("");
  React.useEffect(() => {
    setOut("");
    if (!text) return;
    let i = 0;
    const tick = () => {
      i++;
      setOut(text.slice(0, i));
      if (i < text.length) timer = setTimeout(tick, speed);
    };
    let timer = setTimeout(tick, speed);
    return () => clearTimeout(timer);
  }, [text, speed]);
  return out;
}

// One message rendered in the terminal log
function TerminalEntry({ entry }) {
  const typed = useTypewriter(entry.role === 'assistant' && entry.streaming ? entry.text : "", 12);
  if (entry.role === 'user') {
    return (
      <div className="term-line term-cmd">
        <span className="term-prompt">~ ❯</span>
        <span className="term-text">{entry.text}</span>
      </div>
    );
  }
  if (entry.role === 'system') {
    return (
      <div className="term-line term-out">
        <span className="term-text dim">{entry.text}</span>
      </div>
    );
  }
  if (entry.role === 'thinking') {
    return (
      <div className="term-line term-out">
        <span className="term-text"><span className="term-accent">✦</span> <span className="term-thinking">thinking <i className="term-bdot"/><i className="term-bdot"/><i className="term-bdot"/></span></span>
      </div>
    );
  }
  // assistant
  const text = entry.streaming ? typed : entry.text;
  return (
    <div className="term-line term-out term-reply">
      <span className="term-prompt term-prompt-bot">▸</span>
      <span className="term-text">{text}{entry.streaming && text.length < entry.text.length && <span className="term-cursor">▍</span>}</span>
    </div>
  );
}

const INTRO_LOG = [
  { role: 'user', text: 'whoami', delay: 600 },
  { role: 'system', text: 'chetan.batra', delay: 1200 },
  { role: 'system', text: 'role: gtm-engineer · sales-operator-turned-builder', delay: 1500 },
  { role: 'system', text: 'based: new delhi · ⌨ working us/eu hours', delay: 1800 },
  { role: 'system', text: '', delay: 2000 },
  { role: 'system', text: 'this terminal is live. ask me anything about chetan, his journey, or what he builds.', delay: 2200 },
  { role: 'system', text: 'try one of the suggestions ↓ or just type.', delay: 2400 },
];

function Terminal() {
  const [log, setLog] = React.useState([]);
  const [input, setInput] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [history, setHistory] = React.useState([]); // for LLM context
  const inputRef = React.useRef(null);
  const scrollRef = React.useRef(null);

  // Stream intro
  React.useEffect(() => {
    INTRO_LOG.forEach((entry, i) => {
      setTimeout(() => {
        setLog((l) => [...l, entry]);
      }, entry.delay);
    });
  }, []);

  // Auto-scroll on new entries
  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [log, busy]);

  // Easter eggs — handled locally without hitting the LLM
  const easterEgg = (q) => {
    const cmd = q.toLowerCase().trim();
    if (cmd === 'ls' || cmd === 'ls -la') return [
      { role: 'system', text: 'drwxr-xr-x  journey/         5 jobs, 1 pivot' },
      { role: 'system', text: 'drwxr-xr-x  builds/          6 projects, 2 shipping' },
      { role: 'system', text: '-rw-r--r--  clay-workflows  ∞' },
      { role: 'system', text: '-rw-r--r--  coffee.log      questionable' },
    ];
    if (cmd === 'clear' || cmd === 'cls') return 'CLEAR';
    if (cmd === 'sudo' || cmd.startsWith('sudo ')) return [{ role: 'system', text: 'nice try.' }];
    if (cmd === 'git status') return [
      { role: 'system', text: 'on branch: main' },
      { role: 'system', text: 'untracked files: a few ideas in my head, not committed yet' },
      { role: 'system', text: 'nothing to push. working tree (mostly) clean.' },
    ];
    if (cmd === 'whoami') return [{ role: 'system', text: 'chetan.batra' }];
    if (cmd === 'exit' || cmd === 'quit') return [{ role: 'system', text: "you can't leave. this is the whole site." }];
    if (cmd === 'help' || cmd === '?') return [
      { role: 'system', text: 'commands: ls · clear · git status · whoami · sudo · exit' },
      { role: 'system', text: 'or just ask me anything in plain english.' },
    ];
    return null;
  };

  const send = async (raw) => {
    const q = (raw ?? input).trim();
    if (!q || busy) return;
    setInput("");
    const userEntry = { role: 'user', text: q };

    const egg = easterEgg(q);
    if (egg === 'CLEAR') { setLog([]); return; }
    if (egg) { setLog((l) => [...l, userEntry, ...egg]); return; }

    setLog((l) => [...l, userEntry, { role: 'thinking', text: '' }]);
    setBusy(true);

    const newHistory = [...history, { role: 'user', content: q }];

    try {
      const response = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ messages: newHistory }),
      });
      if (!response.ok) throw new Error('API error');
      const data = await response.json();
      const text = (data.text || '').trim() || "hmm, my brain is buffering. try again?";
      setHistory([...newHistory, { role: 'assistant', content: text }]);
      setLog((l) => {
        const trimmed = l.filter((e) => e.role !== 'thinking');
        return [...trimmed, { role: 'assistant', text, streaming: true }];
      });
      // Mark non-streaming after typewriter likely done
      const dur = Math.min(8000, text.length * 14 + 400);
      setTimeout(() => {
        setLog((l) => l.map((e) => e.role === 'assistant' && e.streaming ? { ...e, streaming: false } : e));
      }, dur);
    } catch (err) {
      setLog((l) => {
        const trimmed = l.filter((e) => e.role !== 'thinking');
        return [...trimmed, { role: 'assistant', text: "the brain is offline rn. try again in a sec?", streaming: false }];
      });
    } finally {
      setBusy(false);
      setTimeout(() => inputRef.current?.focus(), 50);
    }
  };

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

  return (
    <div className="terminal terminal-live" onClick={() => inputRef.current?.focus()}>
      <div className="term-bar">
        <div className="term-dots">
          <i style={{ background: "#ff5f57" }} />
          <i style={{ background: "#febc2e" }} />
          <i style={{ background: "#28c840" }} />
        </div>
        <div className="term-title"><span className="mono">chetan@batra ~ </span><span className="dim mono">live · <span data-term-model>claude-haiku-4.5</span></span></div>
        <div className="term-spacer">
          <span className="live-pip" title="live"><i/>live</span>
        </div>
      </div>
      <div className="term-body" ref={scrollRef}>
        {log.map((entry, i) => <TerminalEntry key={i} entry={entry} />)}
        <div className="term-input-row">
          <span className="term-prompt">~ ❯</span>
          <input
            ref={inputRef}
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={onKey}
            placeholder={busy ? "" : "type a question and hit enter..."}
            className="term-input"
            spellCheck={false}
            autoComplete="off"
            disabled={busy}
          />
          {!busy && <span className="term-cursor blink">▍</span>}
        </div>
      </div>
      <div className="term-suggestions">
        {SUGGESTIONS.map((s) => (
          <button key={s} className="term-suggest" onClick={() => send(s)} disabled={busy}>
            {s}
          </button>
        ))}
      </div>
    </div>
  );
}

function Hero() {
  const [tickerIdx, setTickerIdx] = React.useState(0);
  const tickerWords = ["workflows.", "agents.", "outbound systems.", "weird scrapers.", "claygent flows.", "vibes."];
  React.useEffect(() => {
    const id = setInterval(() => setTickerIdx((i) => (i + 1) % tickerWords.length), 2200);
    return () => clearInterval(id);
  }, []);

  return (
    <section id="top" className="hero section">
      <div className="hero-bg-grid" aria-hidden="true" />
      <div className="container hero-grid">
        <div className="hero-copy">
          <div className="hero-badges hero-anim hero-anim-1">
            <div className="chip">
              <span className="led" />
              <span>shipping <strong>2 builds</strong> this week</span>
            </div>
            <div className="chip chip-warm">
              <span className="mono">↗</span>
              <span>vibe-coding since 2025</span>
            </div>
          </div>
          <h1 className="hero-title hero-anim hero-anim-2">
            <span className="hero-hand">hi, i'm</span>
            <br />
            <span className="hero-name">chetan</span>
            <span className="hero-period">.</span>
          </h1>
          <p className="hero-tag hero-anim hero-anim-3">
            i build <span className="hero-ticker">
              <span key={tickerIdx} className="serif accent-text">{tickerWords[tickerIdx]}</span>
            </span>{' '}
            mostly with <span className="hover-pop">clay</span>, <span className="hover-pop">claygent</span>, a few llms, and questionable amounts of coffee. five years on the phone before this — that's the bit nobody else has.
          </p>
          <div className="hero-meta hero-anim hero-anim-4">
            <span className="mono dim">currently:</span>
            <span>gtm engineer @ <a href="https://www.gravitee.io/" target="_blank" rel="noreferrer" className="underline-wobble">gravitee</a></span>
            <span className="dim">·</span>
            <span>building in public</span>
            <span className="dim">·</span>
            <span>open to interesting convos</span>
          </div>
        </div>
        <div className="hero-term-wrap hero-anim hero-anim-5">
          <Terminal />
          <div className="hero-term-caption mono dim">
            ↑ this is real. powered by an llm. ask away · try <span className="mono">`ls`</span> or <span className="mono">`help`</span>.
          </div>
        </div>
      </div>
      <div className="hero-scroll">
        <span className="mono">scroll · or keep typing</span>
        <svg width="10" height="14" viewBox="0 0 10 14" fill="none">
          <path d="M5 1v12m0 0L1 9m4 4 4-4" stroke="currentColor" strokeWidth="1" strokeLinecap="round" />
        </svg>
      </div>
    </section>
  );
}

window.Hero = Hero;
