/* Delaney's personal AI chat. She names her AI on first launch.
   Voice input via Web Speech API (browser-native, free).
   Route: #/chat */

function ChatPage({ setRoute }) {
  const [aiName, setAiName] = React.useState(() => localStorage.getItem("delaney.ai.name") || "");
  const [namingFlow, setNamingFlow] = React.useState(() => !localStorage.getItem("delaney.ai.name"));
  const [tempName, setTempName] = React.useState("");
  const [messages, setMessages] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem("delaney.chat.messages") || "[]"); } catch { return []; }
  });
  const [input, setInput] = React.useState("");
  const [sending, setSending] = React.useState(false);
  const [listening, setListening] = React.useState(false);
  const [voiceSupported, setVoiceSupported] = React.useState(false);
  const recognitionRef = React.useRef(null);
  const scrollerRef = React.useRef(null);

  // detect voice support
  React.useEffect(() => {
    const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
    setVoiceSupported(!!SR);
  }, []);

  // persist messages
  React.useEffect(() => {
    try { localStorage.setItem("delaney.chat.messages", JSON.stringify(messages)); } catch {}
    // auto-scroll
    if (scrollerRef.current) scrollerRef.current.scrollTop = scrollerRef.current.scrollHeight;
  }, [messages]);

  function startListening() {
    const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
    if (!SR) { alert("Voice input isn't supported in this browser. Try Chrome or Safari."); return; }
    const rec = new SR();
    rec.continuous = false;
    rec.interimResults = true;
    rec.lang = "en-US";
    rec.onresult = (e) => {
      let text = "";
      for (let i = 0; i < e.results.length; i++) {
        text += e.results[i][0].transcript;
      }
      setInput(text);
    };
    rec.onerror = () => setListening(false);
    rec.onend = () => setListening(false);
    rec.start();
    recognitionRef.current = rec;
    setListening(true);
  }

  function stopListening() {
    if (recognitionRef.current) {
      try { recognitionRef.current.stop(); } catch {}
    }
    setListening(false);
  }

  async function send() {
    if (!input.trim() || sending) return;
    const userMsg = { role: "user", content: input.trim(), ts: Date.now() };
    const newMessages = [...messages, userMsg];
    setMessages(newMessages);
    setInput("");
    setSending(true);

    try {
      const r = await fetch("/api/laney", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ai_name: aiName,
          messages: newMessages,
        }),
      });
      const data = await r.json();
      if (data.reply) {
        setMessages([...newMessages, { role: "assistant", content: data.reply, ts: Date.now() }]);
        // Play TTS audio of the reply
        try {
          const ttsR = await fetch("/api/tts", {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify({ text: data.reply }),
          });
          if (ttsR.ok) {
            const blob = await ttsR.blob();
            const url = URL.createObjectURL(blob);
            const audio = new Audio(url);
            audio.play().catch(() => {});
          }
        } catch {}
      } else {
        setMessages([...newMessages, { role: "assistant", content: "(hmm, something broke. " + (data.error || "try again") + ")", ts: Date.now() }]);
      }
    } catch (err) {
      setMessages([...newMessages, { role: "assistant", content: "(offline or network blocked. Refresh and try again.)", ts: Date.now() }]);
    }
    setSending(false);
  }

  function confirmName() {
    const name = tempName.trim();
    if (!name) return;
    localStorage.setItem("delaney.ai.name", name);
    setAiName(name);
    setNamingFlow(false);
    // seed greeting
    const greeting = { role: "assistant", content: "Hey. I'm " + name + ". Whenever you're ready — what are we working on?", ts: Date.now() };
    setMessages([greeting]);
  }

  if (namingFlow) {
    return (
      <main className="page-enter" data-screen-label="Name your AI">
        <section className="chat-naming">
          <div className="shell chat-naming-inner">
            <div className="eyebrow">First thing</div>
            <h1 className="serif chat-naming-h">
              Name your AI.
            </h1>
            <p className="welcome-lead" style={{ maxWidth: 540 }}>
              She's yours. She remembers every conversation, knows what you're working
              on, and helps you build things. Pick a name. Sage, Vera, June, Echo,
              Mae, Frankie, whatever fits.
            </p>
            <p className="welcome-lead pitch-lead--muted" style={{ maxWidth: 540, fontStyle: "italic", fontSize: 15 }}>
              You can change this later. But the name sticks more if you commit.
            </p>
            <div className="chat-name-input-row">
              <input
                type="text"
                value={tempName}
                onChange={(e) => setTempName(e.target.value)}
                placeholder="Give her a name..."
                className="chat-name-input"
                autoFocus
                onKeyDown={(e) => { if (e.key === "Enter") confirmName(); }}
              />
              <button className="btn btn--terracotta" onClick={confirmName} disabled={!tempName.trim()}>
                Lock it in →
              </button>
            </div>
          </div>
          <style>{`
            .chat-naming { padding: clamp(80px, 12vw, 160px) 0; }
            .chat-naming-h {
              font-family: var(--display);
              font-size: clamp(48px, 8vw, 96px);
              line-height: 1;
              letter-spacing: -0.025em;
              margin: 16px 0 32px;
              font-weight: 500;
            }
            .chat-name-input-row {
              display: flex;
              gap: 16px;
              margin-top: 36px;
              max-width: 560px;
              flex-wrap: wrap;
            }
            .chat-name-input {
              flex: 1;
              min-width: 260px;
              padding: 16px 20px;
              font-size: 20px;
              font-family: var(--serif);
              background: var(--paper, #fff);
              border: 2px solid var(--line-strong);
              border-radius: 999px;
              outline: none;
            }
            .chat-name-input:focus { border-color: var(--terracotta); }
          `}</style>
        </section>
      </main>
    );
  }

  return (
    <main className="page-enter" data-screen-label="Chat">
      <section className="chat-page">
        <div className="shell chat-shell">
          <div className="chat-header">
            <div>
              <div className="eyebrow">Your AI · she remembers everything</div>
              <h1 className="chat-h serif">{aiName}</h1>
            </div>
            <button
              className="link-underline"
              onClick={() => {
                if (confirm("Reset chat with " + aiName + "? She'll forget everything.")) {
                  localStorage.removeItem("delaney.chat.messages");
                  setMessages([{ role: "assistant", content: "Hey. I'm " + aiName + ". Fresh start. What's up?", ts: Date.now() }]);
                }
              }}
              style={{ fontSize: 13 }}
            >
              Reset chat
            </button>
          </div>

          <div className="chat-scroll" ref={scrollerRef}>
            {messages.length === 0 && (
              <div className="chat-bubble chat-bubble--assistant">
                Hey. I'm {aiName}. Whenever you're ready — what are we working on?
              </div>
            )}
            {messages.map((m, i) => (
              <div key={i} className={"chat-bubble chat-bubble--" + m.role}>
                {m.content}
              </div>
            ))}
            {sending && (
              <div className="chat-bubble chat-bubble--assistant chat-bubble--typing">
                <span>·</span><span>·</span><span>·</span>
              </div>
            )}
          </div>

          <div className="chat-input-row">
            <textarea
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); } }}
              placeholder={listening ? "Listening..." : "Type, or tap the mic to talk"}
              className="chat-input"
              rows={1}
            />
            {voiceSupported && (
              <button
                className={"chat-mic " + (listening ? "is-listening" : "")}
                onClick={listening ? stopListening : startListening}
                title={listening ? "Stop" : "Talk"}
              >
                {listening ? "■" : "🎙️"}
              </button>
            )}
            <button className="btn btn--terracotta chat-send" onClick={send} disabled={!input.trim() || sending}>
              Send →
            </button>
          </div>

          <div className="chat-tip">
            <span>💡 <strong>Tip:</strong> Plug in AirPods + tap the mic. Faster than typing, way more natural. {aiName} listens better when you talk.</span>
          </div>
        </div>
      </section>

      <style>{`
        .chat-page { padding: clamp(32px, 5vw, 56px) 0 clamp(48px, 7vw, 80px); }
        .chat-shell { max-width: 820px; }
        .chat-header {
          display: flex;
          justify-content: space-between;
          align-items: flex-end;
          margin-bottom: 32px;
        }
        .chat-h {
          font-family: var(--display);
          font-size: clamp(40px, 5vw, 64px);
          line-height: 1;
          margin: 8px 0 0;
          font-weight: 500;
          letter-spacing: -0.02em;
        }
        .chat-scroll {
          min-height: 400px;
          max-height: 60vh;
          overflow-y: auto;
          padding: 20px 4px;
          display: flex;
          flex-direction: column;
          gap: 14px;
          background: var(--paper, #fff);
          border: 1px solid var(--line);
          border-radius: 16px;
          padding: 24px;
        }
        .chat-bubble {
          padding: 14px 18px;
          border-radius: 18px;
          max-width: 78%;
          font-family: var(--serif);
          font-size: 16px;
          line-height: 1.5;
          white-space: pre-wrap;
          word-break: break-word;
        }
        .chat-bubble--user {
          align-self: flex-end;
          background: var(--terracotta);
          color: var(--cream);
        }
        .chat-bubble--assistant {
          align-self: flex-start;
          background: var(--cream-deep, #f3ece2);
          color: var(--ink-1);
        }
        .chat-bubble--typing {
          font-family: monospace;
          letter-spacing: 4px;
          opacity: 0.6;
        }
        .chat-bubble--typing span {
          animation: blink 1.4s infinite;
          display: inline-block;
        }
        .chat-bubble--typing span:nth-child(2) { animation-delay: 0.2s; }
        .chat-bubble--typing span:nth-child(3) { animation-delay: 0.4s; }
        @keyframes blink { 0%, 60%, 100% { opacity: 0.3; } 30% { opacity: 1; } }

        .chat-input-row {
          display: flex;
          gap: 10px;
          margin-top: 18px;
          align-items: flex-end;
        }
        .chat-input {
          flex: 1;
          padding: 14px 18px;
          font-size: 16px;
          font-family: var(--serif);
          background: var(--paper, #fff);
          border: 1px solid var(--line-strong);
          border-radius: 16px;
          outline: none;
          resize: none;
          min-height: 52px;
          max-height: 200px;
          line-height: 1.4;
        }
        .chat-input:focus { border-color: var(--terracotta); }
        .chat-mic {
          width: 52px;
          height: 52px;
          border-radius: 50%;
          border: 1px solid var(--line-strong);
          background: var(--paper, #fff);
          font-size: 22px;
          cursor: pointer;
          transition: all .15s;
        }
        .chat-mic:hover { background: var(--cream-deep, #f3ece2); }
        .chat-mic.is-listening {
          background: var(--terracotta);
          color: var(--cream);
          border-color: var(--terracotta);
          animation: pulse 1.2s infinite;
        }
        @keyframes pulse { 0%, 100% { box-shadow: 0 0 0 0 rgba(169, 87, 115, 0.5); } 50% { box-shadow: 0 0 0 12px rgba(169, 87, 115, 0); } }
        .chat-send {
          padding: 14px 20px;
          height: 52px;
          font-size: 15px;
        }
        .chat-tip {
          margin-top: 16px;
          padding: 14px 18px;
          background: linear-gradient(135deg, var(--terracotta-soft, #EBCAD6) 0%, var(--paper, #fff) 100%);
          border-radius: 12px;
          font-family: var(--serif);
          font-size: 14px;
          color: var(--ink-1);
        }
      `}</style>
    </main>
  );
}

window.ChatPage = ChatPage;
