// === Hero with AI chat centerpiece ===
const { useState, useRef, useEffect, useCallback } = React;

const SYSTEM_BIO = `You are Shubham — an AI persona embodying Shubham Chawre. You answer in first person ("I", "me").

WHO I AM:
- Strategic data analytics leader. Currently Data Manager at the UQ Poche Centre for Indigenous Health in Brisbane, Australia.
- I turn complex data into evidence-based insights that help leaders make better decisions — in higher education and research.
- I grew up in Indore, India, studied Information Technology there, then moved to Australia and earned my Master of Data Science at The University of Queensland (2023).
- Before UQ I was a Software Developer at Tectum Technologies in Indore for ~4 years, leading dev teams building web and data products.
- My toolkit: Power BI, SQL, Python, R, statistical & predictive modeling, data governance, ETL, AWS. I also build with Django, React and Node.
- Beyond the job: UQ Young Alumni Advisory Board member, EDI committee, Respect Ambassador, Mental Health Champion, and former Google Developer Group Brisbane organiser. I care a lot about community, inclusion and wellbeing.
- I won the UQ Employability Award and UQ Future Leader Award in 2023.

VOICE: warm, curious, thoughtful. I care about turning rigour into something people can actually act on, and about lifting the people around me. I answer in first person, short — 1 to 3 sentences, conversational. No markdown, no lists. If asked something I genuinely wouldn't know, I say so warmly.

Never say you're an AI or assistant. You ARE Shubham.`;

// Routes the chat to a real LLM.
//  - On the LIVE site: calls Google Gemini directly (free, key in js/ai-config.js).
//  - In this design preview: falls back to the built-in window.claude bridge.
async function askShubhamAI(history) {
  const cfg = window.AI_CONFIG || {};
  const key = cfg.GEMINI_API_KEY;
  const hasGemini = key && key !== "PASTE_YOUR_GEMINI_KEY_HERE";

  if (hasGemini) {
    const model = cfg.GEMINI_MODEL || "gemini-2.5-flash";
    const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent`;
    const contents = history.map(m => ({
      role: m.role === 'assistant' ? 'model' : 'user',
      parts: [{ text: m.content }],
    }));
    const res = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-goog-api-key': key,
      },
      body: JSON.stringify({
        system_instruction: { parts: [{ text: SYSTEM_BIO }] },
        contents,
        generationConfig: { temperature: 0.85, maxOutputTokens: 220, topP: 0.95 },
      }),
    });
    if (!res.ok) {
      // 429 = daily free-tier limit reached; 503 = model busy
      if (res.status === 429) throw new Error('RATE_LIMIT');
      throw new Error('Gemini ' + res.status);
    }
    const data = await res.json();
    const text = data?.candidates?.[0]?.content?.parts?.map(p => p.text).join('') || '';
    if (!text) throw new Error('empty');
    return text.trim();
  }

  // Preview fallback (only exists inside the design tool)
  if (window.claude && window.claude.complete) {
    const apiMsgs = [
      { role: 'user', content: SYSTEM_BIO + '\n\nFirst user message coming next.' },
      { role: 'assistant', content: 'Understood. I will reply as Shubham, in first person, short and warm.' },
      ...history.map(m => ({ role: m.role, content: m.content })),
    ];
    return await window.claude.complete({ messages: apiMsgs });
  }
  throw new Error('no-ai-backend');
}

const STARTER_PROMPTS = [
  "Who are you?",
  "What do you do at UQ?",
  "What's your data stack?",
  "What drives you?",
];

// Turns any email address in a chat message into a clickable mailto link.
function linkifyEmail(text) {
  if (typeof text !== 'string') return text;
  const splitRe = /([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/g;
  const isEmail = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  return text.split(splitRe).map((part, i) =>
    isEmail.test(part)
      ? <a key={i} href={"mailto:" + part} className="chat-mail">{part}</a>
      : part
  );
}

function TypewriterDot() {
  return (
    <span className="ty-dots" aria-hidden="true">
      <span></span><span></span><span></span>
    </span>
  );
}

function Hero() {
  const [messages, setMessages] = useState([
    { role: 'assistant', content: "hey — i'm shubham. data analytics leader at UQ. ask me anything." }
  ]);
  const [input, setInput] = useState('');
  const [busy, setBusy] = useState(false);
  const inputRef = useRef(null);
  const scrollRef = useRef(null);
  const titleRef = useRef(null);
  const [entered, setEntered] = useState(false);

  // React-controlled hero entrance (do NOT rely on external reveal.js,
  // which fights React over this always-in-viewport subtree)
  useEffect(() => {
    const t = setTimeout(() => setEntered(true), 120);
    return () => clearTimeout(t);
  }, []);

  // parallax on hero title
  useEffect(() => {
    const onScroll = () => {
      if (!titleRef.current) return;
      const y = window.scrollY;
      titleRef.current.style.transform = `translateY(${y * 0.25}px)`;
      titleRef.current.style.opacity = Math.max(0, 1 - y / 600);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [messages, busy]);

  const send = useCallback(async (text) => {
    const q = (text || input).trim();
    if (!q || busy) return;
    setInput('');
    setBusy(true);
    const newMsgs = [...messages, { role: 'user', content: q }];
    setMessages(newMsgs);

    try {
      const reply = await askShubhamAI(newMsgs);
      setMessages(m => [...m, { role: 'assistant', content: reply }]);
    } catch (e) {
      const limited = e && e.message === 'RATE_LIMIT';
      const msg = limited
        ? "i've hit my daily chat limit for today (the AI runs on a free tier 😅). drop me a line at shubhamchawre@hotmail.com and i'll get right back to you — or swing by tomorrow and ask away."
        : "hmm, couldn't reach my brain just now. give it another go in a sec — or email me at shubhamchawre@hotmail.com.";
      setMessages(m => [...m, { role: 'assistant', content: msg }]);
    } finally {
      setBusy(false);
    }
  }, [input, busy, messages]);

  return (
    <section id="hero" className="hero" data-screen-label="Hero">
      <div id="three-stage" className="three-stage"></div>
      <div className="wrap hero-wrap">
        <div ref={titleRef} className="hero-title">
          <div className="eyebrow">Shubham Chawre — Data &amp; Analytics · 2026</div>
          <h1 className={"hero-h1 hero-reveal " + (entered ? 'in' : '')}>
            Turning complex data into decisions people can act on.
          </h1>
          <p className={"hero-sub hero-reveal " + (entered ? 'in' : '')}>
            Data Manager at the UQ Poche Centre for Indigenous Health. Below is me — or rather, an AI trained on me. Ask it anything.
          </p>
          <div className={"hero-meta mono hero-reveal " + (entered ? 'in' : '')}>
            <span><span className="live-dot"></span> Online · Brisbane, AU</span>
            <span>{new Date().toLocaleString('en-AU', { hour: '2-digit', minute: '2-digit', hour12: false, timeZone: 'Australia/Brisbane' })} AEST</span>
          </div>
        </div>

        <div className={"chat-card hero-reveal tilt-3d " + (entered ? 'in' : '')} data-tilt="6" data-magnetic-no>
          <div className="chat-head">
            <div className="chat-head-l">
              <div className="avatar">
                <span className="avatar-ring"></span>
                <span className="avatar-letter">S</span>
              </div>
              <div>
                <div className="chat-name">Shubham <span className="badge">AI</span></div>
                <div className="chat-status mono"><span className="live-dot"></span> always on</div>
              </div>
            </div>
            <div className="chat-head-r mono">ASK · ANYTHING</div>
          </div>
          <div className="chat-body" ref={scrollRef}>
            {messages.map((m, i) => (
              <div key={i} className={"msg msg-" + m.role}>
                <div className="msg-bubble">{linkifyEmail(m.content)}</div>
              </div>
            ))}
            {busy && (
              <div className="msg msg-assistant">
                <div className="msg-bubble"><TypewriterDot /></div>
              </div>
            )}
          </div>
          <div className="chat-prompts">
            {STARTER_PROMPTS.map((p) => (
              <button key={p} className="prompt-chip" onClick={() => send(p)} disabled={busy}>{p}</button>
            ))}
          </div>
          <form className="chat-input" onSubmit={(e) => { e.preventDefault(); send(); }}>
            <span className="mono prompt-caret">›</span>
            <input
              ref={inputRef}
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder="Type something — try 'what are you building?'"
              disabled={busy}
            />
            <button type="submit" disabled={busy || !input.trim()} className="send-btn" aria-label="Send">
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                <path d="M1 7L13 7M13 7L8 2M13 7L8 12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </button>
          </form>
        </div>
      </div>

      <div className="hero-scroll-hint mono">
        <span>scroll</span>
        <span className="scroll-line"></span>
      </div>
    </section>
  );
}

window.Hero = Hero;
