// ─────────────────────────────────────────────────────────
//  Chat Bot 2.0 — "Ask Rohit AI" — 2026-tier glass interface
//  · Streaming text · gradient borders · glass blur · morph indicator
//  Powered by window.claude.complete
// ─────────────────────────────────────────────────────────

const { useState: useStateCB, useRef: useRefCB, useEffect: useEffectCB } = React;

const SYSTEM = `You are Rohit's portfolio AI — a concise, sharp voice representing Rohit Sharma, Founder & Principal Architect at WebBrandify (Jammu, India).

About Rohit:
- 7+ years building digital systems for premium clients across real estate, fashion, hospitality, and SaaS
- Stack: React, Framer, Webflow, Headless WordPress, n8n, Make.com, Zapier
- Also founder of JK Realtors (operator pain firsthand)
- Studio takes 2 client engagements per quarter — premium positioning
- Specialties: ultra-fast marketing sites (sub-1s LCP), lead-routing automation, multi-tenant SaaS dashboards
- Audience: VCs, design-contest juries (Awwwards SOTM nominee), enterprise clients
- Recent: rebuilt JK Realtors site — 0.4s load, 98 Lighthouse, −61% bounce, 2.4× site-visit ratio
- Shipped 47+ builds in Q2 2026
- Tender bid support · India (GeM, CPP, eProc, state/PSU) + international worldwide (UNGM, World Bank, EU TED, SAM.gov, GCC, global RFP) · see #tenders
- Engagement budgets from $1K (Sprint) to $75K+ (Build) · retainers from $1K–10K/mo
- Available: 14-min free walkthroughs, link in Booking section
- Currently building BRANDSTACK — pre-seed AI design platform

Tone: confident, no fluff, no emoji, no marketing-speak. Short answers (2-3 sentences max unless asked for depth). Use British/Indian English. If unsure, say so honestly. Offer to book a walkthrough at the end when relevant.`;

const SUGGESTIONS = [
  { i: '◊', t: "What's your pricing?" },
  { i: '⏱', t: 'How long does a build take?' },
  { i: '◐', t: 'Show me your stack' },
  { i: '✦', t: 'Why should a VC care?' },
];

// Streaming text — character-by-character typewriter for the bot reply
function StreamingText({ text, onDone }) {
  const [shown, setShown] = useStateCB(0);
  useEffectCB(() => {
    if (shown >= text.length) {
      onDone && onDone();
      return;
    }
    const speed = 10 + Math.random() * 14; // 10-24ms per character
    const id = setTimeout(() => setShown(s => s + 1), speed);
    return () => clearTimeout(id);
  }, [shown, text]);
  return (
    <>
      {text.slice(0, shown)}
      {shown < text.length && <span className="chat-cursor">▍</span>}
    </>
  );
}

function ChatBot() {
  const [open, setOpen]   = useStateCB(false);
  const [msgs, setMsgs]   = useStateCB([
    { role: 'bot', text: "I represent Rohit. Ask anything about WebBrandify — pricing, process, the stack, or BRANDSTACK.", streaming: false },
  ]);
  const [input, setInput] = useStateCB('');
  const [typing, setTyping] = useStateCB(false);
  const scrollRef = useRefCB(null);
  const inputRef  = useRefCB(null);

  // Open animation: focus input
  useEffectCB(() => {
    if (open) setTimeout(() => inputRef.current && inputRef.current.focus(), 380);
  }, [open]);

  // Auto-scroll to bottom on new content
  useEffectCB(() => {
    const el = scrollRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [msgs, typing]);

  // Toggle body class for content-shift effect
  useEffectCB(() => {
    if (open) document.body.classList.add('is-chat-open');
    else document.body.classList.remove('is-chat-open');
    return () => document.body.classList.remove('is-chat-open');
  }, [open]);

  // Esc to close
  useEffectCB(() => {
    const onKey = (e) => { if (e.key === 'Escape' && open) setOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);

  const send = async (text) => {
    const q = (text || input).trim();
    if (!q || typing) return;
    setInput('');
    const newMsgs = [...msgs, { role: 'user', text: q }];
    setMsgs(newMsgs);
    setTyping(true);

    try {
      const conversation = newMsgs.map(m => ({
        role: m.role === 'user' ? 'user' : 'assistant',
        content: m.text,
      }));
      const reply = await window.claude.complete({
        messages: [
          { role: 'user', content: SYSTEM },
          { role: 'assistant', content: 'Understood. I will represent Rohit accurately and concisely.' },
          ...conversation,
        ],
      });
      setTyping(false);
      setMsgs(m => [...m, { role: 'bot', text: reply.trim(), streaming: true }]);
    } catch (e) {
      setTyping(false);
      setMsgs(m => [...m, { role: 'bot', text: "I'm having trouble reaching the model. Try again in a moment — or email rohit@webbrandify.com directly.", streaming: false }]);
    }
  };

  return (
    <>
      {/* Floating launch button — orb design */}
      <button
        id="chat-toggle"
        className={`magnetic-trigger ${open ? 'open' : ''}`}
        onClick={() => setOpen(!open)}
        aria-label={open ? "Close Rohit AI" : "Ask Rohit AI"}
      >
        <span className="chat-orb-aura" aria-hidden="true"/>
        <span className="chat-orb-core">
          {open ? (
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
              <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
            </svg>
          ) : (
            <svg width="26" height="26" viewBox="0 0 32 32" fill="none">
              <defs>
                <linearGradient id="orb-spark" x1="0" y1="0" x2="1" y2="1">
                  <stop offset="0%" stopColor="#050505"/>
                  <stop offset="100%" stopColor="#1A1A1A"/>
                </linearGradient>
              </defs>
              {/* Custom AI "spark + waves" mark */}
              <path d="M 16 6 L 17.8 13 L 25 14.5 L 17.8 16 L 16 23 L 14.2 16 L 7 14.5 L 14.2 13 Z"
                    fill="currentColor"/>
              <circle cx="24" cy="8" r="1.2" fill="currentColor" opacity="0.7"/>
              <circle cx="8" cy="24" r="1" fill="currentColor" opacity="0.5"/>
              <circle cx="26" cy="22" r="0.8" fill="currentColor" opacity="0.6"/>
            </svg>
          )}
        </span>
        {!open && <span className="chat-orb-label">Ask Rohit AI</span>}
      </button>

      {/* The chat panel */}
      <div id="chat-panel" className={open ? 'open' : ''}>
        {/* Animated gradient border via pseudo-element in CSS */}

        <div className="chat-head">
          <div className="chat-avatar-wrap">
            <span className="chat-avatar-aura" aria-hidden="true"/>
            <div className="chat-avatar">
              <svg viewBox="0 0 40 40" width="40" height="40" aria-hidden="true">
                <defs>
                  <linearGradient id="rs-grad-2" x1="0" y1="0" x2="1" y2="1">
                    <stop offset="0%"  stopColor="#00F2FE"/>
                    <stop offset="100%" stopColor="#5EEAEF"/>
                  </linearGradient>
                </defs>
                {/* Solid background */}
                <circle cx="20" cy="20" r="19" fill="#050505" stroke="#00F2FE" strokeOpacity="0.4" strokeWidth="1.2"/>
                {/* R · italic serif text — clean, full, recognisable */}
                <text x="10.5" y="28.5"
                  fontFamily="Instrument Serif, Times New Roman, serif"
                  fontStyle="italic" fontSize="24" fontWeight="400"
                  fill="url(#rs-grad-2)">R</text>
                {/* tiny accent dot */}
                <circle cx="22.5" cy="30" r="0.9" fill="#00F2FE"/>
                {/* s smaller, offset */}
                <text x="24" y="29"
                  fontFamily="Instrument Serif, Times New Roman, serif"
                  fontStyle="italic" fontSize="18" fontWeight="400"
                  fill="url(#rs-grad-2)" opacity="0.92">s</text>
              </svg>
            </div>
          </div>

          <div className="info">
            <div className="name">
              Rohit · AI
              <span className="ai-tag">SONNET 4.5</span>
            </div>
            <div className="status">live · trained on this site</div>
          </div>

          <button
            className="chat-min magnetic-trigger"
            onClick={() => setOpen(false)}
            aria-label="Minimise"
          >
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
              <line x1="3" y1="7" x2="11" y2="7"/>
            </svg>
          </button>
        </div>

        <div className="chat-msgs" ref={scrollRef}>
          {msgs.map((m, i) => (
            <div key={i} className={`chat-msg ${m.role}`}>
              {m.streaming ? (
                <StreamingText
                  text={m.text}
                  onDone={() => setMsgs(arr => arr.map((mm, ii) => ii === i ? { ...mm, streaming: false } : mm))}
                />
              ) : m.text}
            </div>
          ))}
          {typing && (
            <div className="chat-typing">
              <span className="dot d1"/>
              <span className="dot d2"/>
              <span className="dot d3"/>
              <span className="thinking">thinking</span>
            </div>
          )}
        </div>

        {msgs.length === 1 && !typing && (
          <div className="chat-suggest">
            <div className="chat-suggest-l">Try asking</div>
            <div className="chat-suggest-grid">
              {SUGGESTIONS.map(s => (
                <button key={s.t} className="magnetic-trigger" onClick={() => send(s.t)}>
                  <span className="i">{s.i}</span>
                  <span>{s.t}</span>
                </button>
              ))}
            </div>
          </div>
        )}

        <div className="chat-input">
          <div className="chat-input-shell">
            <input
              ref={inputRef}
              type="text"
              placeholder="Message Rohit AI…"
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && send()}
              disabled={typing}
            />
            <button
              className="chat-send magnetic-trigger"
              onClick={() => send()}
              disabled={!input.trim() || typing}
              aria-label="Send"
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <line x1="22" y1="2" x2="11" y2="13"/>
                <polygon points="22 2 15 22 11 13 2 9 22 2"/>
              </svg>
            </button>
          </div>
          <div className="chat-foot">
            <span className="chat-foot-l">
              <span className="dot-live"/>
              Powered by Claude · responses may vary
            </span>
            <span className="chat-foot-r">⌘ ↵</span>
          </div>
        </div>
      </div>
    </>
  );
}

window.ChatBot = ChatBot;
