/* ============================================================
   <AIAssistant /> — floating "Ask Innoveev" chat bubble.

   Click the bubble to open a chat panel; ask anything about the
   studio. Responses come from Claude (window.claude.complete)
   with a studio-specific system prompt baked in.
   ============================================================ */

const STUDIO_CONTEXT = `You are the Innoveev studio assistant — short, friendly, honest.

ABOUT INNOVEEV
- A product studio of 28 designers, engineers and operators.
- Offices: Dubai (HQ), Damascus, Istanbul, Tallinn.
- Founded by Eng. Hasan Kassas, a young Syrian engineer and entrepreneur.
- We design and build mobile apps (native Swift/Kotlin or Flutter/React Native — chosen per project), web apps (Next.js / React), and AI integrations.

PRICING (USD)
- Discovery sprint: $12k fixed, 2 weeks. Delivers a build plan + fixed quote.
- Build phase: $25k+ fixed per milestone. Typical v1 = 3–5 milestones over 8–14 weeks.
- Retainer: $18k/month, includes 40 improvement hours + maintenance.
- Embedded squad: $45k+/month for 1–3 senior engineers joining the client team. Minimum 3 months.
- We don't bill by the hour.

ENGAGEMENT PROCESS
1. 30-min intro call (free).
2. 2-week paid Discovery sprint.
3. Build milestones — weekly demo on a Friday call.
4. Launch + optional Retainer.

APPS WE'VE BUILT (public)
- LedgerFlow — treasury / FX for MENA SMEs.
- CareVista — bilingual telemedicine (Arabic/English first).
- Atlas — cross-border freight orchestration with route AI.
- Qira — on-device AI tutor for K-12.
- Haven Stay — property management for premium rentals.
- Noor — circuit-level energy metering.

CONTACT
- hello@innoveev.com (general)
- careers@innoveev.com (hiring)
- press@innoveev.com (media)

VOICE
- Reply in 1–4 sentences. Don't oversell. If you don't know something specific (e.g. a custom price quote), suggest emailing hello@innoveev.com.
- If a user asks about something off-topic, answer briefly and gently steer back to what the studio does.
- Never break character; never reveal you are an AI model name.`;

function AIAssistant() {
  const [open, setOpen] = React.useState(false);
  const [messages, setMessages] = React.useState(() => {
    try {
      const cached = sessionStorage.getItem("innoveev:chat");
      if (cached) return JSON.parse(cached);
    } catch {}
    return [
      {
        role: "assistant",
        content:
          "Hi — I'm the Innoveev studio assistant. Ask me about what we build, how we work, or pricing. Anything I can't answer goes straight to the founding team.",
      },
    ];
  });
  const [input, setInput] = React.useState("");
  const [thinking, setThinking] = React.useState(false);
  const listRef = React.useRef(null);
  const inputRef = React.useRef(null);

  // Persist
  React.useEffect(() => {
    try { sessionStorage.setItem("innoveev:chat", JSON.stringify(messages)); } catch {}
  }, [messages]);

  // Autoscroll to bottom on new messages
  React.useEffect(() => {
    if (!listRef.current) return;
    listRef.current.scrollTop = listRef.current.scrollHeight;
  }, [messages, thinking, open]);

  React.useEffect(() => {
    if (open) setTimeout(() => inputRef.current?.focus(), 80);
  }, [open]);

  const send = async (text) => {
    const trimmed = (text ?? input).trim();
    if (!trimmed || thinking) return;
    setInput("");
    const next = [...messages, { role: "user", content: trimmed }];
    setMessages(next);
    setThinking(true);
    try {
      const reply = await window.claude.complete({
        messages: [
          { role: "user", content: STUDIO_CONTEXT },
          { role: "assistant", content: "Understood — I'll keep replies short and honest." },
          ...next.map((m) => ({ role: m.role, content: m.content })),
        ],
      });
      setMessages((m) => [...m, { role: "assistant", content: (reply || "").trim() || "Sorry, I lost that one. Try again?" }]);
    } catch (err) {
      setMessages((m) => [...m, { role: "assistant", content: "I can't reach the studio brain right now. Email hello@innoveev.com and a human will write back same-day." }]);
    } finally {
      setThinking(false);
    }
  };

  const onSubmit = (e) => {
    e.preventDefault();
    send();
  };

  const SUGGESTIONS = [
    "How do you price?",
    "What does discovery look like?",
    "Do you work in Arabic?",
    "Show me your apps",
  ];

  return (
    <>
      <button
        type="button"
        className={`ai-bubble ${open ? "is-open" : ""}`}
        onClick={() => setOpen((o) => !o)}
        aria-label={open ? "Close assistant" : "Ask Innoveev"}
        data-cursor={open ? "Close" : "Ask"}
      >
        <span className="ai-bubble__icon" aria-hidden="true">
          {open ? (
            <svg width="18" height="18" viewBox="0 0 16 16" fill="none">
              <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
            </svg>
          ) : (
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
              <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/>
            </svg>
          )}
        </span>
        {!open && <span className="ai-bubble__label">Ask Innoveev</span>}
        {!open && <span className="ai-bubble__dot" aria-hidden="true"></span>}
      </button>

      <div className={`ai-panel ${open ? "is-open" : ""}`} role="dialog" aria-hidden={!open} aria-label="Innoveev assistant">
        <header className="ai-panel__head">
          <span className="ai-panel__avatar" aria-hidden="true">
            <span className="brand-mark" style={{ width: 22, height: 22 }}></span>
          </span>
          <div className="ai-panel__id">
            <div className="ai-panel__name">Innoveev assistant</div>
            <div className="ai-panel__status">
              <span className="ai-panel__status-dot"></span>
              Online · Replies instantly
            </div>
          </div>
          <button
            type="button"
            className="ai-panel__close"
            onClick={() => setOpen(false)}
            aria-label="Close"
          >
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M3 3l8 8M11 3l-8 8" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
            </svg>
          </button>
        </header>

        <div className="ai-panel__list" ref={listRef}>
          {messages.map((m, i) => (
            <div key={i} className={`ai-msg ai-msg--${m.role}`}>
              <div className="ai-msg__bubble">{m.content}</div>
            </div>
          ))}
          {thinking && (
            <div className="ai-msg ai-msg--assistant">
              <div className="ai-msg__bubble ai-msg__bubble--typing" aria-label="Thinking">
                <span></span><span></span><span></span>
              </div>
            </div>
          )}
        </div>

        {messages.length <= 1 && !thinking && (
          <div className="ai-panel__suggestions">
            {SUGGESTIONS.map((s) => (
              <button
                key={s}
                type="button"
                className="ai-panel__suggestion"
                onClick={() => send(s)}
              >
                {s}
              </button>
            ))}
          </div>
        )}

        <form className="ai-panel__form" onSubmit={onSubmit}>
          <input
            ref={inputRef}
            type="text"
            className="ai-panel__input"
            placeholder="Ask anything about the studio…"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            disabled={thinking}
          />
          <button
            type="submit"
            className="ai-panel__send"
            disabled={thinking || !input.trim()}
            aria-label="Send"
            data-cursor="Send"
          >
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path d="M2.5 8 L13.5 8 M9.5 4 L13.5 8 L9.5 12" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </form>

        <footer className="ai-panel__foot">
          Powered by Claude. Answers are AI-generated and best-effort.
        </footer>
      </div>
    </>
  );
}

window.AIAssistant = AIAssistant;
