// Transdigital AI chat widget — DeepSeek-V3 via Supabase Edge Function
// API key lives server-side as a Supabase secret (DEEPSEEK_API_KEY)
const SUPABASE_URL      = "https://kecvpvsisbfwyxwjekat.supabase.co";
const SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImtlY3ZwdnNpc2Jmd3l4d2pla2F0Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTU1NDE1NTksImV4cCI6MjA3MTExNzU1OX0.gP_N4lDA1wGSCCucZDb50lVX4kV6wzuUeJA3pZHokkw";
const TD_TENANT_ID      = "237ebf61-40fd-4260-a900-a25c4a9f4907";

async function chatStream(history) {
  const res = await fetch(`${SUPABASE_URL}/functions/v1/ai-chat`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${SUPABASE_ANON_KEY}`,
    },
    body: JSON.stringify({ history }),
  });

  if (!res.ok) {
    const body = await res.text();
    throw new Error(`${res.status}: ${body}`);
  }

  return res;
}


const FORM_I18N = {
  en: {
    title: "Leave us a message",
    sub: "We'll reply within one business day.",
    name: "Full name *",
    email: "Email *",
    interest: "Area of interest",
    message: "Message",
    submit: "Send message",
    sending: "Sending…",
    sent: "Sent — we'll reply within one business day.",
    error: "Something went wrong — please try again.",
    interests: ["Software Licensing","AEC / BIM","Digital Identity","Adobe Creative Cloud","Software Advisory","Tech Support","Other"],
  },
  pt: {
    title: "Deixe-nos uma mensagem",
    sub: "Responderemos em um dia útil.",
    name: "Nome completo *",
    email: "Email *",
    interest: "Área de interesse",
    message: "Mensagem",
    submit: "Enviar mensagem",
    sending: "A enviar…",
    sent: "Enviado — responderemos em um dia útil.",
    error: "Algo correu mal — tente novamente.",
    interests: ["Licenciamento de Software","AEC / BIM","Identidade Digital","Adobe Creative Cloud","Consultoria","Suporte Técnico","Outro"],
  },
};

const WELCOME = "Olá / Hi — ask me anything about Transdigital's platforms, vendor partnerships or services. I'll reply in whatever language you write in.";
const ERROR_MSG = "I'm having trouble connecting right now — please try again in a moment.";

const { useState: csState, useEffect: csEffect, useRef: csRef } = React;

function ChatContactForm({ lang }) {
  const fi = FORM_I18N[lang] || FORM_I18N.en;
  const [fields, setFields] = csState({ name: "", email: "", interest: fi.interests[0], message: "" });
  const [status, setStatus] = csState("idle");

  const set = (k, v) => setFields(f => ({ ...f, [k]: v }));

  const submit = async () => {
    if (!fields.name.trim() || !fields.email.trim()) return;
    setStatus("submitting");
    try {
      const sb = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
      const { error } = await sb.functions.invoke("submit-ticket", {
        body: { ...fields, tenant_id: TD_TENANT_ID },
      });
      if (error) throw error;
      setStatus("sent");
    } catch (_) {
      setStatus("error");
    }
  };

  if (status === "sent") {
    return <p className="td-chat-form-sent">{fi.sent}</p>;
  }

  return (
    <div className="td-chat-form">
      <p className="td-chat-form-title">{fi.title}</p>
      <p className="td-chat-form-sub">{fi.sub}</p>
      <input
        className="td-chat-form-field"
        placeholder={fi.name}
        value={fields.name}
        onChange={e => set("name", e.target.value)}
        disabled={status === "submitting"}
        autoComplete="name"
      />
      <input
        className="td-chat-form-field"
        type="email"
        placeholder={fi.email}
        value={fields.email}
        onChange={e => set("email", e.target.value)}
        disabled={status === "submitting"}
        autoComplete="email"
      />
      <select
        className="td-chat-form-field"
        value={fields.interest}
        onChange={e => set("interest", e.target.value)}
        disabled={status === "submitting"}
      >
        {fi.interests.map(opt => <option key={opt} value={opt}>{opt}</option>)}
      </select>
      <textarea
        className="td-chat-form-field td-chat-form-textarea"
        placeholder={fi.message}
        value={fields.message}
        onChange={e => set("message", e.target.value)}
        disabled={status === "submitting"}
      />
      <button
        className="td-chat-form-submit"
        onClick={submit}
        disabled={status === "submitting" || !fields.name.trim() || !fields.email.trim()}
      >
        {status === "submitting" ? fi.sending : fi.submit}
      </button>
      {status === "error" && <p className="td-chat-form-err">{fi.error}</p>}
    </div>
  );
}

function ChatWidget({ lang = "en" }) {
  const [open, setOpen]        = csState(false);
  const [msgs, setMsgs]        = csState([]);
  const [input, setInput]      = csState("");
  const [streaming, setStream] = csState(false);
  const bottomRef = csRef(null);
  const inputRef  = csRef(null);

  csEffect(() => { bottomRef.current?.scrollIntoView({ behavior: "smooth" }); }, [msgs]);
  csEffect(() => { if (open) setTimeout(() => inputRef.current?.focus(), 80); }, [open]);

  const send = async () => {
    const text = input.trim();
    if (!text || streaming) return;

    const userMsg = { role: "user", text };

    // Build OpenAI-format history for the edge function
    const history = [
      ...msgs
        .map(m => ({
          role: m.role === "model" ? "assistant" : m.role,
          content: m.type === "contact_form"
            ? (m.prelude || "[I showed the user a contact form]")
            : m.text,
        }))
        .filter(m => m.content),
      { role: "user", content: text },
    ];

    setMsgs(prev => [...prev, userMsg, { role: "model", text: "" }]);
    setInput("");
    setStream(true);

    try {
      const res = await chatStream(history);
      const reader = res.body.getReader();
      const dec = new TextDecoder();
      let buf = "";

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        buf += dec.decode(value, { stream: true });
        const lines = buf.split("\n");
        buf = lines.pop() || "";
        for (const line of lines) {
          if (!line.startsWith("data: ")) continue;
          if (line === "data: [DONE]") continue;
          try {
            const part = JSON.parse(line.slice(6))?.choices?.[0]?.delta?.content || "";
            if (!part) continue;
            setMsgs(prev => {
              const c = [...prev];
              c[c.length - 1] = { role: "model", text: c[c.length - 1].text + part };
              return c;
            });
          } catch (_) {}
        }
      }

      // After streaming: detect <<CONTACT_FORM>> and swap message type
      setMsgs(prev => {
        const next = [...prev];
        const last = next[next.length - 1];
        if (last.role === "model" && last.text.includes("<<CONTACT_FORM>>")) {
          const prelude = last.text.replace(/<<CONTACT_FORM>>/g, "").trim();
          next[next.length - 1] = { role: "model", type: "contact_form", prelude };
        }
        return next;
      });
    } catch (_) {
      setMsgs(prev => {
        const c = [...prev];
        c[c.length - 1] = { role: "model", text: ERROR_MSG };
        return c;
      });
    }

    setStream(false);
  };

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

  return (
    <>
      {open && (
        <div className="td-chat-panel" role="dialog" aria-label="Transdigital AI assistant">
          <div className="td-chat-header">
            <span><span className="td-chat-dot" aria-hidden="true" />// TRANSDIGITAL-AI // ONLINE</span>
            <button className="td-chat-close" onClick={() => setOpen(false)} aria-label="Close chat">[ × ]</button>
          </div>

          <div className="td-chat-body">
            {msgs.length === 0 && (
              <p className="td-chat-welcome">{WELCOME}</p>
            )}
            {msgs.map((m, i) => (
              <div key={i} className={`td-chat-msg td-chat-msg--${m.role}`}>
                {m.role === "model" && <span className="td-chat-tag" aria-hidden="true">TD-AI ›</span>}
                <span className="td-chat-text">
                  {m.type === "contact_form" ? (
                    <>
                      {m.prelude && <span>{m.prelude}</span>}
                      <ChatContactForm lang={lang} />
                    </>
                  ) : (
                    <>
                      {m.text}
                      {streaming && i === msgs.length - 1 && m.role === "model" && (
                        <span className="td-cursor" aria-hidden="true" />
                      )}
                    </>
                  )}
                </span>
              </div>
            ))}
            <div ref={bottomRef} />
          </div>

          <div className="td-chat-foot">
            <input
              ref={inputRef}
              className="td-chat-input"
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={onKey}
              placeholder="Ask about vendors, services, licensing…"
              disabled={streaming}
              autoComplete="off"
              aria-label="Chat message"
            />
            <button
              className="td-chat-send"
              onClick={send}
              disabled={streaming || !input.trim()}
              aria-label="Send message"
            >↑</button>
          </div>
        </div>
      )}

      <button
        className={`td-chat-fab${open ? " td-chat-fab--open" : ""}`}
        onClick={() => setOpen(o => !o)}
        aria-label={open ? "Close assistant" : "Open AI assistant"}
      >
        {open ? "[ × ]" : lang === "pt" ? "PERGUNTAR" : "ASK AI"}
      </button>
    </>
  );
}

Object.assign(window, { ChatWidget });
