// TRANS-LOG AI chat widget — DeepSeek + inline request form
const DEEPSEEK_API_KEYS = [
  "sk-00745691faff4d51bee31f29c5ea356c", // sk-... from platform.deepseek.com
];

const SUPABASE_URL      = "https://kecvpvsisbfwyxwjekat.supabase.co";
const SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImtlY3ZwdnNpc2Jmd3l4d2pla2F0Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTU1NDE1NTksImV4cCI6MjA3MTExNzU1OX0.gP_N4lDA1wGSCCucZDb50lVX4kV6wzuUeJA3pZHokkw";
const TENANT_ID         = "a2f6087f-cf1c-4198-a9b2-0bc1c80943ba";

const INTERESTS = [
  "Computing & IT hardware",
  "Engineering & industrial",
  "Banking hardware",
  "Tech Support",
  "Mixed / not sure yet",
];

let _keyIdx = 0;

async function deepseekStream(history) {
  const total = DEEPSEEK_API_KEYS.length;
  for (let attempt = 0; attempt < total; attempt++) {
    const key = DEEPSEEK_API_KEYS[_keyIdx];
    const messages = [
      { role: "system", content: SYSTEM_PROMPT },
      ...history.map(m => ({
        role: m.role === "model" ? "assistant" : "user",
        content: m.text,
      })),
    ];
    const res = await fetch("https://api.deepseek.com/chat/completions", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${key}`,
      },
      body: JSON.stringify({
        model: "deepseek-chat",
        messages,
        stream: true,
        max_tokens: 512,
        temperature: 0.65,
      }),
    });
    if (res.ok) return res;
    if (res.status === 429 || res.status === 402 || res.status === 503) {
      _keyIdx = (_keyIdx + 1) % total;
      continue;
    }
    throw new Error(`${res.status}`);
  }
  throw new Error("all_keys_exhausted");
}

function detectInterest(msgs) {
  const text = msgs.map(m => m.text).join(" ").toLowerCase();
  if (/bank|cash|atm|currency|cheque|teller|\bpos\b|card.?reader|money.?count|coin|counterfeit|vanstone|avansa|safe\b|payment.?terminal/.test(text)) return "Banking hardware";
  if (/rugged|engineer|industrial|factory|plant|automation|plc|hmi|machin|mil-std|ip6[78]|scanner|barcode|field.?op|wareho/.test(text)) return "Engineering & industrial";
  if (/support|repair|warrant|broken|fault|not.?work|issue|problem|fix/.test(text)) return "Tech Support";
  if (/comput|laptop|server|workstation|\bpc\b|monitor|printer|network|cisco|dell|\bhp\b|lenovo|ups\b|nvidia|logitech|schneider/.test(text)) return "Computing & IT hardware";
  return "Mixed / not sure yet";
}

const SYSTEM_PROMPT = `You are a concise, helpful assistant for TRANS-LOG — a hardware procurement partner based in Maputo, Mozambique, supplying computing, rugged, engineering and banking hardware across Mozambique and the region.

COMPANY
HQ: Av. Emília Daússe 2221, Maputo — Moçambique | Tel: +258 865 315 027
Sales & quotes: sales@trans-log.africa
Technical support: tec@trans-log.africa

COMPUTING HARDWARE — authorized reseller for Dell, HP, Lenovo, Intel, NVIDIA, Microsoft, Cisco, APC, Logitech, Schneider Electric
- Workstations, laptops, desktops, servers, storage
- Networking (Cisco switches, routers, wireless)
- Power protection: UPS and rack infrastructure (APC)
- Peripherals, monitors, video collaboration (Logitech)
- Industrial automation and energy management (Schneider Electric)

RUGGED HARDWARE — partner: Rugged SA (ruggedsa.co.za)
- Rugged smartphones (e.g. Rugged Phone X11: IP68/IP69K, Android 12, PTT, NFC, 8150mAh)
- Rugged tablets (e.g. Blackview Active 7: 11" Android 15, IP68/IP69, night vision, 10000mAh)
- Rugged notebooks (e.g. ONERugged N15A: 15.6" Windows 11, Intel Core i7, IP65, MIL-STD-810H)
- Rugged scanners and barcode readers
- Use cases: field operations, logistics, warehousing, utilities, manufacturing, extreme environments

BANKING & CASH HANDLING HARDWARE — partners: Avansa (avansa.co.za) and Vanstone (vanstone.com.cn)
Avansa:
- Currency and coin counters (e.g. Money Counter MC200: 1500 bills/min, UV/MG/IR detection)
- Counterfeit detectors
- POS mounts and payment terminal stands (e.g. PayMount 3000)
- Safes, security bags, tamper-proof seals, pay windows, security doors
Vanstone:
- Android POS terminals (e.g. A99: Android 12, 4G, BT5, WiFi)
- mPOS, PIN pads, QR code payment terminals (e.g. V77)
- Traditional POS for retail, restaurant, transportation

ENGINEERING & INDUSTRIAL HARDWARE
- Automation components: PLCs, HMIs, relays, sensors, connectors, terminals
- Test & measurement equipment, oscilloscopes, power supplies
- Structural systems, cabinets, enclosures
- PPE and safety equipment, tools, fixings, cables

SERVICES
- End-to-end procurement: specification, vendor negotiation, import, delivery, installation
- Quotes within 48 hours, no minimum order
- Tech support: warranty management, repairs, spare parts, on-site service

RESPONSE RULES
- Be concise and direct — aim for under 120 words
- Never invent prices; for pricing direct to sales@trans-log.africa
- When a visitor wants a quote or to submit a formal request, tell them to use the "Submit a request" button below the chat
- Respond in the same language the visitor writes in (English or Portuguese)
- If asked something outside TRANS-LOG's scope, say so briefly and offer to help with something related`;

const WELCOME = "Olá / Hi — ask me anything about TRANS-LOG's hardware range, vendor partnerships or procurement services. I'll reply in whatever language you write in.";
const ERROR_MSG = "I'm having trouble connecting right now. Use the \"Submit a request\" button below to send us a message and we'll get back to you within 48 hours.";

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

const EMPTY_FORM = { name: "", email: "", interest: "", message: "" };

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

  const [showForm, setShowForm]   = csState(false);
  const [formData, setFormData]   = csState(EMPTY_FORM);
  const [formStatus, setFStatus]  = csState("idle"); // idle | submitting | done | error

  const bottomRef = csRef(null);
  const inputRef  = csRef(null);

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

  const openForm = () => {
    setFormData(f => ({ ...f, interest: detectInterest(msgs) }));
    setFStatus("idle");
    setShowForm(true);
  };

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

  const submitForm = async (e) => {
    e.preventDefault();
    if (!formData.name.trim() || !formData.email.trim()) return;
    setFStatus("submitting");
    try {
      const sb = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
      const { error } = await sb.functions.invoke("submit-ticket", {
        body: { ...formData, tenant_id: TENANT_ID },
      });
      if (error) throw error;
      setFStatus("done");
    } catch (_) {
      setFStatus("error");
    }
  };

  const send = async () => {
    const text = input.trim();
    if (!text || streaming) return;
    const history = [...msgs, { role: "user", text }];
    setMsgs(history);
    setInput("");
    setStream(true);
    setMsgs(prev => [...prev, { role: "model", text: "" }]);
    try {
      const res = await deepseekStream(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;
          const raw = line.slice(6).trim();
          if (raw === "[DONE]") continue;
          try {
            const part = JSON.parse(raw)?.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 (_) {}
        }
      }
    } 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(); }
  };

  const inputStyle = {
    width: "100%", boxSizing: "border-box",
    background: "var(--td-panel-2)", border: "1px solid var(--td-line)",
    fontFamily: "var(--td-sans)", fontSize: 13, color: "var(--td-fg)",
    padding: "8px 10px", outline: "none", marginBottom: 10,
  };
  const labelStyle = {
    display: "block", fontSize: 10, letterSpacing: "0.1em",
    textTransform: "uppercase", color: "var(--td-fg-mute)", marginBottom: 4,
  };

  return (
    <>
      {open && (
        <div className="td-chat-panel" role="dialog" aria-label="TRANS-LOG AI assistant">

          {/* Header */}
          <div className="td-chat-header">
            {showForm ? (
              <>
                <span>// SUBMIT REQUEST</span>
                <button className="td-chat-close" onClick={() => setShowForm(false)} aria-label="Back to chat">[ ← ]</button>
              </>
            ) : (
              <>
                <span><span className="td-chat-dot" aria-hidden="true" />// TRANS-LOG AI // ONLINE</span>
                <button className="td-chat-close" onClick={() => setOpen(false)} aria-label="Close chat">[ × ]</button>
              </>
            )}
          </div>

          {/* Body — chat or form */}
          {showForm ? (
            <div className="td-chat-body" style={{ padding: "16px 14px" }}>
              {formStatus === "done" ? (
                <div style={{ textAlign: "center", padding: "24px 0" }}>
                  <div style={{ fontSize: 22, marginBottom: 10 }}>✓</div>
                  <p style={{ fontSize: 13, lineHeight: 1.6, color: "var(--td-fg)", margin: 0 }}>
                    Request sent — we'll be in touch within 48 hours.
                  </p>
                  <button
                    onClick={() => { setShowForm(false); setFormData(EMPTY_FORM); }}
                    style={{ marginTop: 16, background: "none", border: "1px solid var(--td-line)", color: "var(--td-fg-mute)", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", padding: "6px 12px", cursor: "pointer" }}
                  >Back to chat</button>
                </div>
              ) : (
                <form onSubmit={submitForm}>
                  <label style={labelStyle}>Full name *</label>
                  <input style={inputStyle} value={formData.name} onChange={e => setField("name", e.target.value)} required disabled={formStatus === "submitting"} />

                  <label style={labelStyle}>Work email *</label>
                  <input style={inputStyle} type="email" value={formData.email} onChange={e => setField("email", e.target.value)} required disabled={formStatus === "submitting"} />

                  <label style={labelStyle}>Company</label>
                  <input style={inputStyle} value={formData.company || ""} onChange={e => setField("company", e.target.value)} disabled={formStatus === "submitting"} />

                  <label style={labelStyle}>I'm enquiring about</label>
                  <select
                    style={{ ...inputStyle, marginBottom: 10, appearance: "none", cursor: "pointer" }}
                    value={formData.interest}
                    onChange={e => setField("interest", e.target.value)}
                    disabled={formStatus === "submitting"}
                  >
                    {INTERESTS.map(opt => <option key={opt} value={opt}>{opt}</option>)}
                  </select>

                  <label style={labelStyle}>Message</label>
                  <textarea
                    style={{ ...inputStyle, resize: "vertical", minHeight: 72 }}
                    value={formData.message}
                    onChange={e => setField("message", e.target.value)}
                    disabled={formStatus === "submitting"}
                  />

                  {formStatus === "error" && (
                    <p style={{ fontSize: 12, color: "#c0392b", margin: "0 0 10px" }}>
                      Something went wrong — please try again.
                    </p>
                  )}

                  <button
                    type="submit"
                    disabled={formStatus === "submitting" || !formData.name.trim() || !formData.email.trim()}
                    style={{
                      width: "100%", background: "var(--td-accent)", color: "#fff", border: "none",
                      fontFamily: "var(--td-mono)", fontSize: 11, fontWeight: 700,
                      letterSpacing: "0.12em", textTransform: "uppercase",
                      padding: "11px", cursor: "pointer", opacity: formStatus === "submitting" ? 0.6 : 1,
                    }}
                  >
                    {formStatus === "submitting" ? "Sending…" : "Send request →"}
                  </button>
                </form>
              )}
            </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">TL-AI ›</span>}
                    <span className="td-chat-text">
                      {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={lang === "pt" ? "Pergunte sobre hardware, fornecedores…" : "Ask about hardware, vendors, quotes…"}
                  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>

              <button className="td-chat-request-btn" onClick={openForm}>
                {lang === "pt" ? "Submeter pedido →" : "Submit a request →"}
              </button>
            </>
          )}

        </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 });
