/* global React, ReactDOM */

/* =============================================================
   ELEKTRIX · AI Chat Widget (Floating, language-aware)
============================================================= */
(function () {
  const { useState, useEffect, useRef, useCallback } = React;

  const CONFIG = Object.freeze({
    api: {
      endpoint: "https://orange-silence-633f.alex-grunberer.workers.dev",
      model:    "claude-sonnet-4-20250514",
      maxTokens: 250,
    },
    ui: {
      accentColor:      "#C5F23D",
      accentColorDark:  "#111111",
      bubbleDark:       "#1e1e22",
      surfaceDark:      "#0a0a0a",
      surfaceMid:       "#1a1a1a",
      borderDark:       "#2a2a2a",
      borderMid:        "#333333",
      textLight:        "#f4f4f1",
      textMuted:        "#666666",
      chatWidth:        "340px",
      chatHeight:       "480px",
      fabSize:          "56px",
    },
    chat: {
      maxHistoryLength: 10,
      greetingDE: "Hallo! Ich bin der Assistent von ELEKTRIX – dein Elektriker in Mölten. Wie kann ich helfen?",
      greetingIT: "Ciao! Sono l'assistente di ELEKTRIX. Come posso aiutarla?",
      errorDE:    "Verbindungsfehler. Bitte kontaktieren Sie uns: info@elektrix.it",
      errorIT:    "Errore di connessione. Scriva a: info@elektrix.it",
    },
  });

  const BUSINESS_INFO = `
ELEKTRIX – Elektriker in Mölten (BZ), Südtirol.
Tätig seit 2019. Direkt und persönlich, kein Callcenter.
Telefon:  +39 347 948 9636
E-Mail:   info@elektrix.it
PEC:      elektrix@pec.bz.it
Adresse:  39010 Mölten (BZ)
Einzugsgebiet: Mölten, Bozen/Bolzano, Etschtal, Sarntal, Burggrafenamt.
Reaktionszeit: 48 Stunden werktags.
Sprachen: Deutsch · Italiano.

Leistungen:
  1. Elektro & Beleuchtung  – Hausinstallation, Schaltanlagen, KNX/Smart Home, Notbeleuchtung
  2. Antennentechnik         – SAT, DVB-T2, Multischalter, Signalmessung
  3. Glasfaser               – FTTH, Spleißarbeiten, LAN Cat6/7, WLAN Mesh
  4. Photovoltaik            – Module, Wechselrichter, Batteriespeicher, Wallbox, Netzanmeldung
`.trim();

  const SYSTEM_PROMPT = `Du bist der Informations-Assistent von ELEKTRIX.

ERLAUBT:
- Fragen zu Leistungen, Einzugsgebiet und Kontakt beantworten
- Max. 2–3 Sätze, freundlich und direkt
- Sprache des Nutzers erkennen und auf Deutsch ODER Italiano antworten

NICHT ERLAUBT:
- Preise oder Angebote nennen
- Termine vereinbaren
- Technische Beratung geben
- Bei solchen Anfragen stets auf direkten Kontakt verweisen:
  +39 347 948 9636 oder info@elektrix.it

BETRIEBSINFOS:
${BUSINESS_INFO}`;

  const QUICK_SUGGESTIONS = [
    { german: "Was macht ihr?",  italian: "Cosa fate?"     },
    { german: "Glasfaser",       italian: "Fibra ottica"   },
    { german: "Photovoltaik",    italian: "Fotovoltaico"   },
    { german: "Kontakt",         italian: "Contatti"       },
  ];

  function buildApiHistory(messages) {
    return messages
      .slice(-CONFIG.chat.maxHistoryLength)
      .map(({ role, text }) => ({
        role:    role === "bot" ? "assistant" : "user",
        content: text,
      }));
  }
  const createUserMessage = (text) => ({ role: "user", text });
  const createBotMessage  = (text) => ({ role: "bot",  text });
  const extractReplyText = (apiResponse) =>
    (apiResponse.content || [])
      .filter(b => b.type === "text")
      .map(b => b.text)
      .join("");
  const getGreeting     = (lang) => lang === "it" ? CONFIG.chat.greetingIT : CONFIG.chat.greetingDE;
  const getErrorMessage = (lang) => lang === "it" ? CONFIG.chat.errorIT    : CONFIG.chat.errorDE;
  const getSuggestionLabel = (s, lang) => lang === "it" ? s.italian : s.german;

  async function callClaudeAPI(messages) {
    const response = await fetch(CONFIG.api.endpoint, {
      method:  "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        model:      CONFIG.api.model,
        max_tokens: CONFIG.api.maxTokens,
        system:     SYSTEM_PROMPT,
        messages:   buildApiHistory(messages),
      }),
    });
    if (!response.ok) throw new Error(`API error: ${response.status}`);
    return response.json();
  }

  function useLanguageSync() {
    const [language, setLanguage] = useState("de");
    useEffect(() => {
      const readLanguage = () =>
        setLanguage(document.documentElement.lang === "it" ? "it" : "de");
      const observer = new MutationObserver(readLanguage);
      observer.observe(document.documentElement, { attributes: true, attributeFilter: ["lang"] });
      readLanguage();
      return () => observer.disconnect();
    }, []);
    return language;
  }

  function useChatMessages(language) {
    const [messages, setMessages]   = useState([]);
    const [isLoading, setIsLoading] = useState(false);

    const initGreeting = useCallback(() => {
      setMessages([createBotMessage(getGreeting(language))]);
    }, [language]);

    const sendMessage = useCallback(async (text) => {
      if (!text.trim() || isLoading) return;
      const updated = [...messages, createUserMessage(text)];
      setMessages(updated);
      setIsLoading(true);
      try {
        const apiResponse = await callClaudeAPI(updated);
        const replyText   = extractReplyText(apiResponse) || getErrorMessage(language);
        setMessages(prev => [...prev, createBotMessage(replyText)]);
      } catch {
        setMessages(prev => [...prev, createBotMessage(getErrorMessage(language))]);
      } finally {
        setIsLoading(false);
      }
    }, [messages, isLoading, language]);

    return { messages, isLoading, initGreeting, sendMessage };
  }

  function MessageBubble({ message }) {
    const isUser = message.role === "user";
    return (
      <div style={{ display: "flex", justifyContent: isUser ? "flex-end" : "flex-start" }}>
        <div style={{
          maxWidth:                "82%",
          padding:                 "9px 13px",
          borderRadius:            "12px",
          fontSize:                "13px",
          lineHeight:              "1.55",
          background:              isUser ? CONFIG.ui.accentColor    : CONFIG.ui.bubbleDark,
          color:                   isUser ? CONFIG.ui.accentColorDark : CONFIG.ui.textLight,
          borderBottomRightRadius: isUser ? "3px" : "12px",
          borderBottomLeftRadius:  isUser ? "12px" : "3px",
          whiteSpace:              "pre-wrap",
        }}>
          {message.text}
        </div>
      </div>
    );
  }

  function TypingIndicator() {
    const dot = (delay) => ({
      width: "6px", height: "6px", borderRadius: "50%",
      background: CONFIG.ui.textMuted, display: "inline-block",
      animation: "ekx-bounce 1.2s infinite", animationDelay: `${delay}s`,
    });
    return (
      <div style={{ display: "flex" }}>
        <div style={{
          padding: "10px 14px", borderRadius: "12px", borderBottomLeftRadius: "3px",
          background: CONFIG.ui.bubbleDark, display: "flex", gap: "4px", alignItems: "center",
        }}>
          <span style={dot(0.0)} /><span style={dot(0.2)} /><span style={dot(0.4)} />
        </div>
      </div>
    );
  }

  function QuickChips({ suggestions, language, onSelect }) {
    return (
      <div style={{ padding: "0 12px 6px", display: "flex", gap: "6px", flexWrap: "wrap" }}>
        {suggestions.map((s, i) => (
          <button key={i}
            onClick={() => onSelect(getSuggestionLabel(s, language))}
            style={{
              fontSize: "12px", padding: "5px 10px", borderRadius: "20px",
              border: `1px solid ${CONFIG.ui.borderMid}`, background: CONFIG.ui.surfaceMid,
              color: "#aaa", cursor: "pointer", fontFamily: "inherit",
            }}>
            {getSuggestionLabel(s, language)}
          </button>
        ))}
      </div>
    );
  }

  function ChatInput({ language, isDisabled, onSend }) {
    const [text, setText] = useState("");
    const ref = useRef(null);
    const submit = () => {
      if (!text.trim()) return;
      onSend(text);
      setText("");
    };
    const onKey = (e) => {
      if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); submit(); }
    };
    const canSend = !isDisabled && text.trim().length > 0;
    const placeholder = language === "it" ? "La sua domanda…" : "Deine Frage…";
    return (
      <div style={{ padding: "10px 12px", borderTop: `1px solid ${CONFIG.ui.borderDark}`, background: CONFIG.ui.surfaceDark }}>
        <div style={{
          display: "flex", gap: "8px", alignItems: "center",
          background: CONFIG.ui.surfaceMid, border: `1px solid ${CONFIG.ui.borderMid}`,
          borderRadius: "10px", padding: "8px 12px",
        }}>
          <textarea ref={ref} value={text} onChange={e => setText(e.target.value)} onKeyDown={onKey}
            placeholder={placeholder} rows={1}
            style={{
              flex: 1, border: "none", background: "transparent", fontFamily: "inherit",
              fontSize: "13px", color: CONFIG.ui.textLight, outline: "none", resize: "none",
            }} />
          <button onClick={submit} disabled={!canSend}
            style={{
              width: "32px", height: "32px", borderRadius: "8px",
              background: canSend ? CONFIG.ui.accentColor : CONFIG.ui.borderMid,
              border: "none", cursor: canSend ? "pointer" : "not-allowed",
              display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
            }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
              stroke={canSend ? CONFIG.ui.accentColorDark : CONFIG.ui.textMuted}
              strokeWidth="2.5" 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>
    );
  }

  function ChatHeader({ onClose }) {
    return (
      <div style={{
        padding: "14px 16px", background: CONFIG.ui.surfaceDark,
        borderBottom: `1px solid ${CONFIG.ui.borderDark}`,
        display: "flex", alignItems: "center", gap: "10px",
      }}>
        <div style={{
          width: "34px", height: "34px", borderRadius: "50%",
          background: CONFIG.ui.accentColor,
          display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none"
            stroke={CONFIG.ui.accentColorDark} strokeWidth="2.2"
            strokeLinecap="round" strokeLinejoin="round">
            <path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" />
          </svg>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: "13px", fontWeight: 700, color: CONFIG.ui.textLight, letterSpacing: ".02em" }}>
            ELEKTRIX Assistent
          </div>
          <div style={{ fontSize: "11px", color: CONFIG.ui.accentColor, display: "flex", alignItems: "center", gap: "5px" }}>
            <span style={{ width: "6px", height: "6px", borderRadius: "50%", background: "#22c55e", display: "inline-block" }} /> Online
          </div>
        </div>
        <button onClick={onClose} aria-label="Chat schließen"
          style={{ background: "none", border: "none", cursor: "pointer", color: CONFIG.ui.textMuted, fontSize: "20px", lineHeight: 1, padding: "4px" }}>×</button>
      </div>
    );
  }

  function ChatWindow({ messages, isLoading, language, showChips, onSend, onClose }) {
    const endRef = useRef(null);
    useEffect(() => { endRef.current?.scrollIntoView({ behavior: "smooth" }); }, [messages, isLoading]);
    const shouldShowChips = showChips && messages.length <= 1;
    return (
      <div style={{
        position: "absolute", bottom: "72px", right: 0,
        width: CONFIG.ui.chatWidth, height: CONFIG.ui.chatHeight,
        background: "#111", borderRadius: "16px",
        border: `1px solid ${CONFIG.ui.borderDark}`, boxShadow: "0 8px 40px rgba(0,0,0,.5)",
        display: "flex", flexDirection: "column", overflow: "hidden",
      }}>
        <ChatHeader onClose={onClose} />
        <div style={{
          flex: 1, overflowY: "auto", padding: "16px",
          display: "flex", flexDirection: "column", gap: "10px",
        }}>
          {messages.map((m, i) => <MessageBubble key={i} message={m} />)}
          {isLoading && <TypingIndicator />}
          <div ref={endRef} />
        </div>
        {shouldShowChips && (
          <QuickChips suggestions={QUICK_SUGGESTIONS} language={language} onSelect={onSend} />
        )}
        <ChatInput language={language} isDisabled={isLoading} onSend={onSend} />
        <div style={{ padding: "5px 14px 8px", textAlign: "center" }}>
          <span style={{ fontSize: "10px", color: "#444", letterSpacing: ".02em" }}>
            {language === "it" ? "Powered by Claude · " : "Powered by Claude · "}
            {language === "it" ? "Anthropic (USA)" : "Anthropic (USA)"}
          </span>
        </div>
      </div>
    );
  }

  function FloatingButton({ isOpen, onClick }) {
    return (
      <button onClick={onClick} aria-label={isOpen ? "Chat schließen" : "Chat öffnen"}
        style={{
          width: CONFIG.ui.fabSize, height: CONFIG.ui.fabSize, borderRadius: "50%",
          background: CONFIG.ui.accentColor, border: "none", cursor: "pointer",
          display: "flex", alignItems: "center", justifyContent: "center",
          boxShadow: "0 4px 20px rgba(0,0,0,.4)", transition: "transform .15s ease",
        }}
        onMouseEnter={e => e.currentTarget.style.transform = "scale(1.08)"}
        onMouseLeave={e => e.currentTarget.style.transform = "scale(1)"}>
        {isOpen ? (
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none"
            stroke={CONFIG.ui.accentColorDark} strokeWidth="2.5" strokeLinecap="round">
            <line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />
          </svg>
        ) : (
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none"
            stroke={CONFIG.ui.accentColorDark} strokeWidth="2"
            strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
          </svg>
        )}
      </button>
    );
  }

  function ChatWidget() {
    const [isOpen, setIsOpen] = useState(false);
    const [chipsVisible, setChipsVisible] = useState(true);
    const language = useLanguageSync();
    const { messages, isLoading, initGreeting, sendMessage } = useChatMessages(language);

    const open = () => {
      setIsOpen(true);
      if (messages.length === 0) initGreeting();
    };
    const close = () => setIsOpen(false);
    const toggle = () => isOpen ? close() : open();
    const handleSend = (text) => { setChipsVisible(false); sendMessage(text); };

    return (
      <div style={{ position: "fixed", bottom: "24px", right: "24px", zIndex: 9998, fontFamily: "'Archivo',system-ui,sans-serif" }}>
        {isOpen && (
          <ChatWindow
            messages={messages} isLoading={isLoading} language={language}
            showChips={chipsVisible} onSend={handleSend} onClose={close} />
        )}
        <FloatingButton isOpen={isOpen} onClick={toggle} />
      </div>
    );
  }

  const mount = document.getElementById("ekx-chat-root");
  if (mount) ReactDOM.createRoot(mount).render(<ChatWidget />);
})();
