/* App entry */

function ScrollToTop() {
  const [visible, setVisible] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setVisible(window.scrollY > 400);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <button
      onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}
      aria-label="Nach oben scrollen"
      style={{
        position: "fixed",
        bottom: "calc(2rem + var(--safe-bottom))",
        right: "max(2rem, var(--safe-right))",
        zIndex: 999,
        width: 48,
        height: 48,
        borderRadius: "50%",
        border: "1px solid rgba(255,255,255,0.12)",
        background: "rgba(10,12,20,0.80)",
        backdropFilter: "blur(16px)",
        WebkitBackdropFilter: "blur(16px)",
        boxShadow: "0 8px 32px rgba(0,0,0,0.45), 0 0 0 1px rgba(21,185,250,0.18)",
        color: "var(--accent-blue)",
        cursor: "pointer",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        opacity: visible ? 1 : 0,
        transform: visible ? "translateY(0)" : "translateY(16px)",
        transition: "opacity 300ms, transform 300ms",
        pointerEvents: visible ? "auto" : "none",
      }}
    >
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
        <polyline points="18 15 12 9 6 15" />
      </svg>
    </button>
  );
}

function FritzChat() {
  const [open, setOpen] = React.useState(false);
  const [greeted, setGreeted] = React.useState(false);
  const [messages, setMessages] = React.useState([]);
  const [input, setInput] = React.useState("");
  const [typing, setTyping] = React.useState(false);
  const endRef = React.useRef(null);

  const fmt = () => new Date().toLocaleTimeString("de-DE", { hour: "2-digit", minute: "2-digit" });

  React.useEffect(() => {
    if (open && !greeted) {
      setGreeted(true);
      setTimeout(() => {
        setMessages([{ from: "fritz", text: "Hallo! Ich bin Fritz, dein KI-Assistent von Scality Solutions 👋 Wie kann ich dir helfen?", ts: fmt() }]);
      }, 400);
    }
  }, [open]);

  React.useEffect(() => {
    endRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages, typing]);

  const send = () => {
    const text = input.trim();
    if (!text) return;
    setInput("");
    setMessages(m => [...m, { from: "user", text, ts: fmt() }]);
    setTyping(true);
    const history = [...messages, { from: "user", text, ts: fmt() }];
    fetch("/api-fritz.php", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ messages: history }),
    })
      .then(r => r.text())
      .then(raw => {
        setTyping(false);
        try {
          const data = JSON.parse(raw);
          if (data.text) {
            setMessages(m => [...m, { from: "fritz", text: data.text, ts: fmt() }]);
          } else {
            setMessages(m => [...m, { from: "fritz", text: "⚠️ " + (data.error || "Unbekannter Fehler") + (data.detail ? ": " + data.detail : ""), ts: fmt() }]);
          }
        } catch {
          setMessages(m => [...m, { from: "fritz", text: "⚠️ Ungültige Antwort vom Server. Ist api-fritz.php hochgeladen?", ts: fmt() }]);
        }
      })
      .catch(err => {
        setTyping(false);
        setMessages(m => [...m, { from: "fritz", text: "⚠️ Datei nicht erreichbar: " + err.message, ts: fmt() }]);
      });
  };

  const blue = "#15b9fa";
  const bubbleBase = {
    maxWidth: "82%",
    padding: "9px 13px",
    borderRadius: 14,
    fontSize: 14,
    lineHeight: 1.5,
    wordBreak: "break-word",
  };

  return (
    <>
      {/* Chat window */}
      <div style={{
        position: "fixed",
        bottom: "calc(5.5rem + var(--safe-bottom))",
        left: "max(1.5rem, var(--safe-left))",
        zIndex: 998,
        width: "min(340px, calc(100vw - 3rem))", maxHeight: "min(520px, 70vh)",
        background: "rgba(8,10,18,0.94)",
        border: "1px solid rgba(255,255,255,0.10)",
        borderRadius: 20,
        boxShadow: `0 24px 60px rgba(0,0,0,0.6), 0 0 0 1px rgba(21,185,250,0.15), 0 0 40px rgba(21,185,250,0.08)`,
        backdropFilter: "blur(24px)", WebkitBackdropFilter: "blur(24px)",
        display: "flex", flexDirection: "column",
        opacity: open ? 1 : 0,
        transform: open ? "translateY(0) scale(1)" : "translateY(16px) scale(0.97)",
        transition: "opacity 280ms cubic-bezier(0.16,1,0.3,1), transform 280ms cubic-bezier(0.16,1,0.3,1)",
        pointerEvents: open ? "auto" : "none",
      }}>
        {/* Header */}
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "14px 16px", borderBottom: "1px solid rgba(255,255,255,0.07)" }}>
          <div style={{ width: 38, height: 38, borderRadius: "50%", background: `linear-gradient(135deg, ${blue}, #0e7fb5)`, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, boxShadow: `0 0 16px ${blue}55` }}>
              <svg width="19" height="19" viewBox="0 0 24 24" fill="white" stroke="none"><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>
            </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: 14.5, color: "#fff", letterSpacing: "-0.01em" }}>Fritz</div>
            <div style={{ fontSize: 11.5, color: "rgba(255,255,255,0.5)", display: "flex", alignItems: "center", gap: 4 }}>
              <span style={{ width: 6, height: 6, borderRadius: "50%", background: "#22c55e", display: "inline-block" }} />
              KI-Assistent · Scality
            </div>
          </div>
          <button onClick={() => setOpen(false)} style={{ background: "none", border: "none", color: "rgba(255,255,255,0.45)", cursor: "pointer", padding: 4, display: "flex", alignItems: "center", borderRadius: 8 }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        </div>

        {/* Messages */}
        <div style={{ flex: 1, overflowY: "auto", padding: "14px 14px 8px", display: "flex", flexDirection: "column", gap: 10, minHeight: 0, maxHeight: 360 }}>
          {messages.map((msg, i) => (
            <div key={i} style={{ display: "flex", flexDirection: "column", alignItems: msg.from === "user" ? "flex-end" : "flex-start" }}>
              <div style={{
                ...bubbleBase,
                background: msg.from === "fritz" ? "rgba(255,255,255,0.07)" : `${blue}22`,
                color: msg.from === "fritz" ? "rgba(255,255,255,0.88)" : "#fff",
                border: msg.from === "fritz" ? "1px solid rgba(255,255,255,0.08)" : `1px solid ${blue}44`,
              }}>{msg.text}</div>
              <div style={{ fontSize: 10.5, color: "rgba(255,255,255,0.25)", marginTop: 3, paddingLeft: 2, paddingRight: 2 }}>{msg.ts}</div>
            </div>
          ))}
          {typing && (
            <div style={{ display: "flex", alignItems: "flex-start" }}>
              <div style={{ ...bubbleBase, background: "rgba(255,255,255,0.07)", border: "1px solid rgba(255,255,255,0.08)", display: "flex", gap: 5, alignItems: "center", padding: "10px 14px" }}>
                {[0,1,2].map(i => <span key={i} style={{ width: 6, height: 6, borderRadius: "50%", background: blue, display: "inline-block", animation: `fritzDot 1.2s ${i*0.2}s ease-in-out infinite` }} />)}
              </div>
            </div>
          )}
          <div ref={endRef} />
        </div>

        {/* Input */}
        <div style={{ padding: "10px 12px 14px", borderTop: "1px solid rgba(255,255,255,0.07)", display: "flex", gap: 8, alignItems: "center" }}>
          <input
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={e => e.key === "Enter" && send()}
            placeholder="Nachricht schreiben..."
            style={{ flex: 1, background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.10)", borderRadius: 12, padding: "9px 13px", color: "#fff", fontSize: 13.5, outline: "none", fontFamily: "inherit" }}
          />
          <button onClick={send} style={{ width: 36, height: 36, borderRadius: 10, background: `linear-gradient(135deg, ${blue}, #0e7fb5)`, border: "none", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, boxShadow: `0 4px 14px ${blue}44` }}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#fff" 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>

      {/* Toggle button */}
      <button
        onClick={() => setOpen(o => !o)}
        aria-label="Chat öffnen"
        style={{
          position: "fixed",
        bottom: "calc(1.5rem + var(--safe-bottom))",
        left: "max(1.5rem, var(--safe-left))",
        zIndex: 999,
          width: 56, height: 56, borderRadius: "50%", border: "none", cursor: "pointer",
          background: `linear-gradient(135deg, ${blue}, #0e7fb5)`,
          boxShadow: `0 8px 28px ${blue}55, 0 0 0 ${open ? 0 : 3}px ${blue}33`,
          display: "flex", alignItems: "center", justifyContent: "center",
          transition: "transform 200ms, box-shadow 200ms",
          animation: open ? "none" : "fritzPulse 2.8s ease-in-out infinite",
        }}
      >
        {open ? (
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#fff" 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="24" height="24" viewBox="0 0 24 24" fill="white" stroke="none"><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>

      <style>{`
        @keyframes fritzPulse { 0%,100%{box-shadow:0 8px 28px #15b9fa55,0 0 0 3px #15b9fa22} 50%{box-shadow:0 8px 28px #15b9fa77,0 0 0 8px #15b9fa11} }
        @keyframes fritzDot { 0%,100%{opacity:0.35;transform:translateY(0)} 50%{opacity:1;transform:translateY(-3px)} }
      `}</style>
    </>
  );
}

function App() {
  return (
    <div className="relative">
      <Navbar />
      <Hero />
      <StatsStrip />
      <VideoAbout />
      <MacBookScroll />
      <Services />
      <HorizontalReferences />
      <PricingStack />
      <Intraware />
      <Testimonials />
      <FAQ />
      <Funnel />
      <Footer />
      <ScrollToTop />
      <FritzChat />
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
