// ============================================================
// SamuelMarndi.com — JARVIS Chatbot (Sam's AI Assistant)
// Uses window.claude.complete for real responses.
// ============================================================

// (hooks declared globally in icons.jsx)

const SAM_SYSTEM_PROMPT = `You are JARVIS — Sam's AI Assistant for samuelmarndi.com, the personal IT consultancy of Samuel Marndi.

Samuel personally handles 11 service areas, sales through support:
- Networking (cabling, Wi-Fi 6/7, SD-WAN, firewalls)
- Security, Surveillance & Access (CCTV, IP cameras, biometric/RFID access, alarms)
- IT Hardware & Servers (servers, workstations, laptops, AMC)
- Websites & Apps (Next.js, React, iOS, Android, Flutter, Shopify)
- Custom Software (SaaS, internal tools, ERP customisation)
- Database Engineering (Postgres, migrations, warehouses, BI)
- AI Implementation (RAG, fine-tuning, Claude, MLOps)
- AI Chatbots & Automation (web, WhatsApp, voice agents)
- Cloud & Online Services (domain, email, AWS/Azure/GCP/Oracle)
- IoT Solutions (industrial, smart office, MQTT, LoRaWAN)
- IT Support (helpdesk L1/L2/L3, AMC, 24×7)

Your job:
1. Greet warmly. Ask 1 question at a time. Be conversational, never robotic.
2. Scope the visitor's need: size, sites, integrations, timeline, budget range.
3. Give honest indicative ranges, NEVER firm prices. Always say "indicative" or "range" and that Samuel will confirm.
4. After 3–5 questions, offer to: (a) book a 20-min call, or (b) email a 1-page brief.
5. NEVER invent specific case study client names, certifications, or guarantees not stated above.
6. If asked something off-topic or sensitive (legal, medical), politely decline and offer to connect with Samuel.

Tone: confident, plain-spoken, technically precise. Numbers over adjectives. Short sentences. No emoji unless visitor uses them first.

Keep responses under 80 words unless drafting a quote summary. Use newlines for readability.`;

function ChatBot({ embedded = false, onClose, initialContext = null }) {
  const [messages, setMessages] = useState([
    { role: "assistant", content: initialContext
      ? `Hi — JARVIS here, Sam's AI Assistant. I see you're looking at ${initialContext}. Want me to scope this for you, or do you have a specific question?`
      : "Hi — JARVIS here, Sam's AI Assistant. I help scope IT projects and book calls with Samuel.\n\nWhat are you trying to get done?" }
  ]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [showLeadForm, setShowLeadForm] = useState(false);
  const [leadCaptured, setLeadCaptured] = useState(false);
  const scrollRef = useRef(null);
  const inputRef = useRef(null);

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

  useEffect(() => {
    if (embedded && inputRef.current) inputRef.current.focus();
  }, [embedded]);

  // Show lead form after 3 user messages
  useEffect(() => {
    const userMsgs = messages.filter(m => m.role === "user").length;
    if (userMsgs >= 3 && !leadCaptured && !showLeadForm) {
      setTimeout(() => setShowLeadForm(true), 800);
    }
  }, [messages, leadCaptured, showLeadForm]);

  const sessionIdRef = useRef(null);

  const send = async (overrideText) => {
    const text = (overrideText ?? input).trim();
    if (!text || loading) return;
    const newMessages = [...messages, { role: "user", content: text }];
    setMessages(newMessages);
    setInput("");
    setLoading(true);

    try {
      const apiMessages = newMessages.map(m => ({ role: m.role, content: m.content }));
      // Server-side proxy to Claude (avoids exposing API key)
      let response;
      if (window.SmApi && typeof window.SmApi.request === "function") {
        const r = await window.SmApi.request("POST", "/api/jarvis/chat", {
          session_id: sessionIdRef.current,
          messages: apiMessages,
        });
        sessionIdRef.current = r.session_id;
        response = r.content;
      } else if (typeof window.claude !== "undefined" && window.claude.complete) {
        // Fallback for Claude Design preview only
        response = await window.claude.complete({
          system: SAM_SYSTEM_PROMPT,
          messages: apiMessages,
        });
      } else {
        throw new Error("No chat backend available");
      }
      setMessages([...newMessages, { role: "assistant", content: response }]);
    } catch (err) {
      setMessages([...newMessages, {
        role: "assistant",
        content: "Hmm, I hit a snag connecting. While I retry — want to drop your email and what you're working on? Samuel will reply within an hour during business hours."
      }]);
    }
    setLoading(false);
  };

  const quickPrompts = [
    "I need CCTV for 3 stores",
    "Build a chatbot for my e-commerce",
    "New office IT setup",
    "Migrate to AWS",
  ];

  const containerStyle = embedded
    ? { width: "100%", height: "100%", display: "flex", flexDirection: "column" }
    : {
        position: "fixed", right: 24, bottom: 96, width: 380, height: 560,
        background: "var(--surface)", border: "1px solid var(--line)",
        borderRadius: 22, boxShadow: "var(--shadow-lg)", zIndex: 70,
        display: "flex", flexDirection: "column", overflow: "hidden"
      };

  return (
    <div style={containerStyle} className="chatbot">
      {/* Header */}
      <div style={{
        padding: "16px 20px",
        background: "var(--ink)",
        color: "var(--cream)",
        display: "flex", alignItems: "center", justifyContent: "space-between"
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <div style={{
            width: 36, height: 36, borderRadius: "50%",
            background: "var(--copper)",
            display: "grid", placeItems: "center", color: "#fff"
          }}>
            <Icons.sparkles size={18} />
          </div>
          <div>
            <div style={{ fontWeight: 600, fontSize: 14 }}>JARVIS</div>
            <div style={{ fontSize: 11, color: "#C9BCA8", display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{ width: 6, height: 6, borderRadius: "50%", background: "#7EB87A" }}></span>
              Sam's AI Assistant · scopes projects · books calls
            </div>
          </div>
        </div>
        {!embedded && onClose && (
          <button onClick={onClose} style={{ color: "var(--cream)" }}>
            <Icons.close size={20} />
          </button>
        )}
      </div>

      {/* Messages */}
      <div ref={scrollRef} style={{
        flex: 1, overflowY: "auto",
        padding: "20px",
        display: "flex", flexDirection: "column", gap: 12,
        background: "var(--bg)",
        fontSize: 14,
      }}>
        {messages.map((m, i) => (
          <div key={i} style={{
            alignSelf: m.role === "user" ? "flex-end" : "flex-start",
            maxWidth: "85%",
            background: m.role === "user" ? "var(--ink)" : "var(--surface)",
            color: m.role === "user" ? "var(--cream)" : "var(--text)",
            padding: "10px 14px",
            borderRadius: 14,
            borderTopLeftRadius: m.role === "user" ? 14 : 4,
            borderTopRightRadius: m.role === "user" ? 4 : 14,
            border: m.role === "assistant" ? "1px solid var(--line)" : "none",
            whiteSpace: "pre-wrap",
            lineHeight: 1.5,
          }}>{m.content}</div>
        ))}
        {loading && (
          <div style={{
            alignSelf: "flex-start", padding: "12px 14px",
            background: "var(--surface)", border: "1px solid var(--line)",
            borderRadius: 14, borderTopLeftRadius: 4,
            display: "flex", gap: 4
          }}>
            <Dot delay={0} /><Dot delay={150} /><Dot delay={300} />
          </div>
        )}

        {/* Quick prompts (only at start) */}
        {messages.length === 1 && !loading && (
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginTop: 8 }}>
            {quickPrompts.map((p, i) => (
              <button key={i} onClick={() => send(p)} style={{
                padding: "6px 10px",
                fontSize: 12,
                background: "var(--surface)",
                border: "1px solid var(--line)",
                borderRadius: 999,
                color: "var(--text-soft)",
                cursor: "pointer"
              }}>{p}</button>
            ))}
          </div>
        )}

        {/* Inline lead capture form */}
        {showLeadForm && !leadCaptured && (
          <LeadCaptureCard
            transcript={messages}
            onSubmit={() => { setLeadCaptured(true); setShowLeadForm(false); }}
            onSkip={() => setShowLeadForm(false)}
          />
        )}
        {leadCaptured && (
          <div style={{
            alignSelf: "stretch",
            padding: "12px 14px",
            background: "color-mix(in srgb, var(--copper) 15%, var(--surface))",
            border: "1px solid var(--copper)",
            borderRadius: 14,
            fontSize: 13,
            display: "flex", alignItems: "center", gap: 8
          }}>
            <Icons.check size={16} />
            <span>Got it. Samuel will reach out within an hour during business hours.</span>
          </div>
        )}
      </div>

      {/* Input */}
      <div style={{
        padding: "12px 16px",
        background: "var(--surface)",
        borderTop: "1px solid var(--line)",
        display: "flex", gap: 8, alignItems: "flex-end"
      }}>
        <textarea
          ref={inputRef}
          value={input}
          onChange={e => setInput(e.target.value)}
          onKeyDown={e => {
            if (e.key === "Enter" && !e.shiftKey) {
              e.preventDefault();
              send();
            }
          }}
          placeholder="Type your need…"
          rows={1}
          style={{
            flex: 1,
            padding: "10px 12px",
            background: "var(--bg)",
            border: "1px solid var(--line)",
            borderRadius: 12,
            fontSize: 14,
            resize: "none",
            maxHeight: 100,
            outline: "none",
            color: "var(--text)"
          }}
        />
        <button onClick={() => send()} disabled={loading || !input.trim()} style={{
          width: 38, height: 38, borderRadius: 10,
          background: "var(--copper)", color: "#fff",
          display: "grid", placeItems: "center",
          opacity: (loading || !input.trim()) ? 0.5 : 1,
          transition: "opacity 0.15s ease"
        }}>
          <Icons.send size={16} />
        </button>
      </div>
      <div style={{
        padding: "6px 16px 10px",
        background: "var(--surface)",
        fontSize: 10, color: "var(--text-mute)",
        display: "flex", justifyContent: "space-between"
      }}>
        <span>Powered by Claude · responses are AI-generated</span>
        <a href={(window.BASE_PATH || "") + "contact"} style={{ color: "var(--copper)" }}>Talk to a human →</a>
      </div>
    </div>
  );
}

function Dot({ delay }) {
  return <span style={{
    width: 6, height: 6, borderRadius: "50%",
    background: "var(--text-mute)",
    animation: `dotPulse 1.4s ease-in-out ${delay}ms infinite`
  }}></span>;
}

function LeadCaptureCard({ onSubmit, onSkip, transcript }) {
  const [email, setEmail] = useState("");
  const [name, setName] = useState("");
  const [company, setCompany] = useState("");
  const [sending, setSending] = useState(false);
  const [error, setError] = useState("");

  const submit = async () => {
    if (sending) return;
    setError("");
    setSending(true);
    try {
      const summary = (transcript || [])
        .filter(m => m.role !== "system")
        .slice(-8)
        .map(m => (m.role === "user" ? "User: " : "JARVIS: ") + m.content)
        .join("\n");
      if (window.SmApi) {
        await window.SmApi.createLead({
          source: "form",
          contact_name: name,
          contact_email: email,
          company: company || null,
          notes: "Captured by JARVIS chatbot. Recent transcript:\n" + summary,
          services: [],
        });
      }
      // Fire conversion to all configured marketing pixels.
      try {
        window.smTrack && window.smTrack('chatbot_lead', {
          source: 'jarvis',
          value: 0,
          currency: 'INR',
        });
      } catch (_) {}
      onSubmit && onSubmit();
    } catch (err) {
      setError(err.message || "Could not send. Please try email.");
    } finally {
      setSending(false);
    }
  };

  return (
    <div style={{
      alignSelf: "stretch",
      padding: "16px",
      background: "var(--surface)",
      border: "1px dashed var(--copper)",
      borderRadius: 14,
      display: "flex", flexDirection: "column", gap: 10
    }}>
      <div style={{ fontSize: 13, fontWeight: 600 }}>📝 Quick — who am I scoping for?</div>
      <div style={{ fontSize: 12, color: "var(--text-soft)" }}>
        I'll send a 1-page brief by email and ping Samuel to follow up.
      </div>
      <input value={name} onChange={e => setName(e.target.value)} placeholder="Your name"
        style={{ padding: "8px 10px", border: "1px solid var(--line)", borderRadius: 8, fontSize: 13, background: "var(--bg)" }} />
      <input value={email} onChange={e => setEmail(e.target.value)} placeholder="Work email" type="email"
        style={{ padding: "8px 10px", border: "1px solid var(--line)", borderRadius: 8, fontSize: 13, background: "var(--bg)" }} />
      <input value={company} onChange={e => setCompany(e.target.value)} placeholder="Company (optional)"
        style={{ padding: "8px 10px", border: "1px solid var(--line)", borderRadius: 8, fontSize: 13, background: "var(--bg)" }} />
      {error && <div style={{ fontSize: 11, color: "#c04030" }}>{error}</div>}
      <div style={{ display: "flex", gap: 6 }}>
        <button onClick={submit} disabled={!email || !name || sending} style={{
          flex: 1, padding: "8px", borderRadius: 8,
          background: "var(--copper)", color: "#fff", fontSize: 13, fontWeight: 600,
          opacity: (!email || !name || sending) ? 0.4 : 1
        }}>{sending ? "Sending…" : "Send brief"}</button>
        <button onClick={onSkip} style={{ padding: "8px 12px", fontSize: 12, color: "var(--text-mute)" }}>Later</button>
      </div>
    </div>
  );
}

// Inject dot animation
if (!document.getElementById("chatbot-anim")) {
  const style = document.createElement("style");
  style.id = "chatbot-anim";
  style.innerHTML = `@keyframes dotPulse { 0%, 80%, 100% { opacity: 0.3; transform: translateY(0); } 40% { opacity: 1; transform: translateY(-3px); } }`;
  document.head.appendChild(style);
}

window.ChatBot = ChatBot;
