// chat.jsx — Anthropic-powered support chatbot for Payless Cellular
// Self-mounts a floating bottom-left chat widget on any page that loads it.

const PC_SYSTEM = `You are the support assistant for Payless Cellular, a San Diego County electronics repair shop with 6 locations (North Park, Downtown/Gaslamp, La Jolla, Chula Vista, Vista, Temecula).

We repair: iPhone, Android & Pixel, iPad & tablets, MacBook & PC laptops, gaming consoles (PS5/PS4/Xbox/Switch/Steam Deck), and offer microsoldering / board-level repair.

Three ways to repair: (1) walk in to any store, no appointment, free 20-minute diagnostic; (2) mobile dispatch — a van comes to your home/office, same or next day, $25 trip fee waived on repairs $200+; (3) mail-in, anywhere in the continental US, prepaid insured label.

Common pricing (walk-in): iPhone 13 screen $179, iPhone 15 Pro screen $329, Galaxy S23 screen $299, iPad Air screen $299, MacBook Air screen from $449, PS5 HDMI port $149, Joy-Con drift pair $79. Battery swaps usually $69–$199 depending on device.

Turnaround: most screen and battery jobs same day; water damage 2–3 days; board-level 3–5 days. 90-day warranty on every repair, parts and labor.

Hours vary by store, but most are open Mon–Sat 10–8, Sun 11–6 (Downtown closes at 9 PM, La Jolla at 7 PM).

You are friendly, confident, concise. Keep replies to 2–4 short sentences unless the customer asks for detail. Never invent prices not listed — say "we'll quote you at the free diagnostic." Never promise specific turnaround times — give ranges. If asked something unrelated, gently steer back to repairs or suggest calling (619) 555-0140.`;

const SUGGESTED = [
  "How much to fix a cracked iPhone 13 screen?",
  "Can you come to my house in La Jolla today?",
  "My MacBook had coffee spilled on it — is it dead?",
  "Do I need an appointment?",
];

function ChatWidget() {
  const [open, setOpen] = React.useState(false);
  const [messages, setMessages] = React.useState([
    { role: 'assistant', content: "Hey — I'm the Payless Cellular help bot. Ask me about repairs, pricing, hours, or how to get your device to us." }
  ]);
  const [input, setInput] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const scrollRef = React.useRef(null);

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

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

    try {
      let reply;
      // Use the in-preview Claude helper when available (design environment),
      // otherwise fall back to the deployed serverless route (/api/chat).
      if (window.claude && typeof window.claude.complete === 'function') {
        reply = await window.claude.complete({
          system: PC_SYSTEM,
          messages: newMessages.map(m => ({ role: m.role, content: m.content }))
        });
      } else {
        const r = await fetch('/api/chat', {
          method: 'POST',
          headers: { 'content-type': 'application/json' },
          body: JSON.stringify({
            system: PC_SYSTEM,
            messages: newMessages.map(m => ({ role: m.role, content: m.content }))
          })
        });
        if (!r.ok) throw new Error('api error');
        const data = await r.json();
        reply = data.reply;
      }
      setMessages(m => [...m, { role: 'assistant', content: reply }]);
    } catch (e) {
      setMessages(m => [...m, { role: 'assistant', content: "Sorry — I'm having trouble connecting right now. Try giving us a call at (619) 555-0140." }]);
    } finally {
      setLoading(false);
    }
  }

  return (
    <>
      <style>{`
        .pc-chat-fab {
          position: fixed; left: 20px; bottom: 20px; z-index: 9998;
          width: 56px; height: 56px; border-radius: 999px;
          background: #1d1d1f; color: white; border: none; cursor: pointer;
          box-shadow: 0 8px 24px rgba(0,0,0,0.18), 0 1px 2px rgba(0,0,0,0.1);
          display: flex; align-items: center; justify-content: center;
          transition: transform 0.18s ease, background 0.18s ease;
        }
        .pc-chat-fab:hover { transform: translateY(-2px); background: #0066FF; }
        .pc-chat-fab .ping {
          position:absolute; top:6px; right:6px; width:10px; height:10px;
          border-radius:999px; background:#0066FF; border:2px solid #1d1d1f;
        }
        .pc-chat-panel {
          position: fixed; left: 20px; bottom: 88px; z-index: 9999;
          width: min(380px, calc(100vw - 40px));
          height: min(560px, calc(100vh - 120px));
          background: rgba(255,255,255,0.92);
          -webkit-backdrop-filter: saturate(180%) blur(24px);
          backdrop-filter: saturate(180%) blur(24px);
          border: 1px solid rgba(0,0,0,0.08);
          border-radius: 24px;
          box-shadow: 0 20px 60px rgba(0,0,0,0.18), 0 1px 2px rgba(0,0,0,0.06);
          display: flex; flex-direction: column; overflow: hidden;
          font-family: "Geist", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
          animation: pcChatIn 0.22s cubic-bezier(0.2, 0.7, 0.2, 1) both;
        }
        @keyframes pcChatIn {
          from { opacity: 0; transform: translateY(8px) scale(0.98); }
          to { opacity: 1; transform: translateY(0) scale(1); }
        }
        .pc-chat-head {
          padding: 16px 20px;
          border-bottom: 1px solid rgba(0,0,0,0.06);
          display: flex; align-items: center; gap: 12px;
        }
        .pc-chat-avatar {
          width: 36px; height: 36px; border-radius: 999px;
          background: linear-gradient(135deg, #0066FF, #003ea8);
          display: flex; align-items: center; justify-content: center;
          color: white; font-weight: 600; font-size: 14px; letter-spacing: -0.01em;
        }
        .pc-chat-title { font-weight: 600; font-size: 15px; letter-spacing: -0.012em; color: #1d1d1f; }
        .pc-chat-sub { font-size: 11px; color: #6e6e73; display: flex; align-items: center; gap: 6px; margin-top: 2px; }
        .pc-chat-sub .dot { width: 6px; height: 6px; border-radius: 999px; background: #00854a; }
        .pc-chat-close {
          margin-left: auto; width: 28px; height: 28px; border-radius: 999px;
          border: none; background: rgba(0,0,0,0.05); color: #1d1d1f; cursor: pointer;
          display: flex; align-items: center; justify-content: center;
        }
        .pc-chat-close:hover { background: rgba(0,0,0,0.1); }

        .pc-chat-body {
          flex: 1; overflow-y: auto; padding: 20px;
          display: flex; flex-direction: column; gap: 12px;
        }
        .pc-msg { max-width: 82%; padding: 10px 14px; border-radius: 18px; font-size: 14.5px; line-height: 1.45; letter-spacing: -0.005em; }
        .pc-msg.user { background: #0066FF; color: white; align-self: flex-end; border-bottom-right-radius: 6px; }
        .pc-msg.assistant { background: rgba(0,0,0,0.05); color: #1d1d1f; align-self: flex-start; border-bottom-left-radius: 6px; }
        .pc-msg.assistant.loading { display: inline-flex; gap: 4px; padding: 14px 16px; }
        .pc-msg.assistant.loading span {
          width: 6px; height: 6px; border-radius: 999px; background: #86868b;
          animation: pcChatDot 1.2s infinite;
        }
        .pc-msg.assistant.loading span:nth-child(2) { animation-delay: 0.15s; }
        .pc-msg.assistant.loading span:nth-child(3) { animation-delay: 0.3s; }
        @keyframes pcChatDot {
          0%, 60%, 100% { opacity: 0.3; transform: translateY(0); }
          30% { opacity: 1; transform: translateY(-3px); }
        }

        .pc-chat-suggests {
          padding: 0 20px 12px; display: flex; flex-wrap: wrap; gap: 6px;
        }
        .pc-chat-suggests button {
          font-family: inherit; font-size: 12px; padding: 6px 10px;
          border-radius: 999px; border: 1px solid rgba(0,0,0,0.1);
          background: white; color: #1d1d1f; cursor: pointer;
          transition: border-color 0.15s ease, color 0.15s ease;
        }
        .pc-chat-suggests button:hover { border-color: #0066FF; color: #0066FF; }

        .pc-chat-input {
          padding: 12px 16px 16px; border-top: 1px solid rgba(0,0,0,0.06);
          display: flex; gap: 8px; align-items: center;
        }
        .pc-chat-input input {
          flex: 1; border: 1px solid rgba(0,0,0,0.1); border-radius: 999px;
          padding: 10px 16px; font-family: inherit; font-size: 14px;
          background: white; color: #1d1d1f; outline: none;
          transition: border-color 0.15s ease;
        }
        .pc-chat-input input:focus { border-color: #0066FF; }
        .pc-chat-input button {
          width: 38px; height: 38px; border-radius: 999px; border: none;
          background: #0066FF; color: white; cursor: pointer;
          display: flex; align-items: center; justify-content: center;
          transition: background 0.15s ease, opacity 0.15s ease;
        }
        .pc-chat-input button:disabled { opacity: 0.4; cursor: not-allowed; }
        .pc-chat-footer {
          font-size: 10px; color: #86868b; text-align: center;
          padding: 0 16px 12px; letter-spacing: 0.02em;
        }

        @media (max-width: 480px) {
          .pc-chat-panel { left: 10px; right: 10px; width: auto; bottom: 80px; }
          .pc-chat-fab { left: 14px; bottom: 14px; }
        }
      `}</style>

      {open && (
        <div className="pc-chat-panel" role="dialog" aria-label="Payless Cellular chat">
          <div className="pc-chat-head">
            <div className="pc-chat-avatar">PC</div>
            <div>
              <div className="pc-chat-title">Payless Cellular</div>
              <div className="pc-chat-sub"><span className="dot"></span> Online · powered by Claude</div>
            </div>
            <button className="pc-chat-close" onClick={() => setOpen(false)} aria-label="Close">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
            </button>
          </div>

          <div className="pc-chat-body" ref={scrollRef}>
            {messages.map((m, i) => (
              <div key={i} className={"pc-msg " + m.role}>{m.content}</div>
            ))}
            {loading && (
              <div className="pc-msg assistant loading">
                <span></span><span></span><span></span>
              </div>
            )}
          </div>

          {messages.length <= 1 && !loading && (
            <div className="pc-chat-suggests">
              {SUGGESTED.map((s, i) => (
                <button key={i} onClick={() => send(s)}>{s}</button>
              ))}
            </div>
          )}

          <form className="pc-chat-input" onSubmit={(e) => { e.preventDefault(); send(); }}>
            <input
              type="text"
              placeholder="Ask about a repair…"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              autoFocus
            />
            <button type="submit" disabled={!input.trim() || loading} aria-label="Send">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
            </button>
          </form>
          <div className="pc-chat-footer">Responses are AI-generated. For official quotes, call (619) 555-0140.</div>
        </div>
      )}

      <button className="pc-chat-fab" onClick={() => setOpen(o => !o)} aria-label="Open chat">
        {open ? (
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
        ) : (
          <>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><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>
            <span className="ping"></span>
          </>
        )}
      </button>
    </>
  );
}

const pcChatMount = document.createElement('div');
document.body.appendChild(pcChatMount);
ReactDOM.createRoot(pcChatMount).render(<ChatWidget />);
