/* Viamar Mobile — Support chat (interactive, with smart replies) */

function smartReply(text) {
  const t = text.toLowerCase();
  if (/where|status|track|location|at sea|how far/.test(t))
    return "Your BMW M4 (VMR-48217) is at sea aboard MV Atlantic Crown — about 62% of the way to Bremerhaven. ETA Jun 14. Want me to open the live map?";
  if (/photo|picture|image|loaded/.test(t))
    return "All 32 loading photos are on file for VMR-48217 — vehicle secured, wheel straps, container seal #. You can open them on the shipment page any time. 📸";
  if (/document|upload|bill of sale|ownership|paperwork|id/.test(t))
    return "You can upload documents right here — tap the paperclip. For vehicles we need ownership, bill of sale and your Canadian ID. Everything for your BMW is already verified ✅.";
  if (/pay|invoice|price|cost|balance|quote/.test(t))
    return "Your BMW is prepaid in full — no balance owing. Your Lisbon household quote locks once we confirm the price (usually within the hour), then you can prepay in the app.";
  if (/deliver|delivery|when|arrive|drop/.test(t))
    return "ETA into Bremerhaven is Jun 14. We'll reach your consignee about 48h before arrival to set a curbside delivery window.";
  if (/customs|duty|inspection|clear/.test(t))
    return "Customs clearance at destination is included. Inspections affect ~10–15% of shipments; any third-party fees are passed on at cost — never marked up.";
  if (/human|agent|call|speak|person|phone/.test(t))
    return "Connecting you with Marco, your dedicated agent — he's online now and usually replies within a few minutes. You can also call 1-800-277-7570. 👋";
  if (/thank|thanks|great|perfect|cheers/.test(t))
    return "Anytime! I'm here 24/7, and Marco is one tap away whenever you need a human. 🙌";
  return "Got it — Marco will jump in shortly. Meanwhile you can track your shipment, or view documents and loading photos from the shipment page.";
}

const QUICK_REPLIES = ["Where's my car?", 'View loading photos', 'Upload a document', 'Delivery date', 'Talk to a human'];

function Bubble({ m }) {
  const me = m.from === 'me';
  if (m.from === 'system') {
    return <div style={{ textAlign: 'center', margin: '6px 0' }}><span style={{ fontFamily: FM, fontSize: 10.5, color: T.faint, letterSpacing: 0.3, background: 'rgba(10,27,46,0.05)', padding: '4px 12px', borderRadius: 999 }}>{m.text}</span></div>;
  }
  return (
    <div className="m-bubble" style={{ display: 'flex', justifyContent: me ? 'flex-end' : 'flex-start', marginBottom: 10 }}>
      <div style={{ maxWidth: '80%' }}>
        <div style={{
          background: me ? T.red : '#fff', color: me ? '#fff' : T.ink,
          borderRadius: me ? '18px 18px 5px 18px' : '18px 18px 18px 5px',
          padding: '11px 14px', fontFamily: FB, fontSize: 14.5, lineHeight: 1.45,
          boxShadow: me ? '0 4px 14px rgba(221,28,36,0.28)' : '0 1px 2px rgba(10,27,46,0.06)',
          border: me ? 'none' : '1px solid ' + T.line2,
        }}>{m.text}</div>
        {m.time && <div style={{ fontFamily: FM, fontSize: 9.5, color: T.faint, marginTop: 4, textAlign: me ? 'right' : 'left', padding: '0 4px' }}>{m.time}</div>}
      </div>
    </div>
  );
}

function ChatScreen({ onBack }) {
  const now = () => new Date().toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
  const [messages, setMessages] = React.useState([
    { from: 'system', text: 'Today' },
    { from: 'agent', text: "Hi Alessandro 👋 I'm your Viamar assistant. I can track shipments, find documents, or hand you to Marco — your agent. How can I help?", time: '9:32 AM' },
    { from: 'agent', text: 'Quick heads-up: your BMW M4 to Bremerhaven is loaded and sailing — ETA Jun 14. 🚢', time: '9:32 AM' },
  ]);
  const [typing, setTyping] = React.useState(false);
  const [input, setInput] = React.useState('');
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    const el = scrollRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [messages, typing]);

  const send = (txt) => {
    const text = (txt != null ? txt : input).trim();
    if (!text) return;
    setInput('');
    setMessages(m => [...m, { from: 'me', text, time: now() }]);
    setTyping(true);
    setTimeout(() => {
      setTyping(false);
      setMessages(m => [...m, { from: 'agent', text: smartReply(text), time: now() }]);
    }, 1100);
  };

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: T.paper }}>
      {/* header */}
      <div style={{ background: T.navy, padding: '54px 16px 14px', flexShrink: 0, boxShadow: '0 1px 0 rgba(255,255,255,0.06)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <div onClick={onBack} style={{ width: 34, height: 34, borderRadius: 10, background: 'rgba(255,255,255,0.08)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flexShrink: 0 }}>
            <Icon name="chevL" size={19} color="#fff" stroke={2.2} />
          </div>
          <div style={{ position: 'relative', flexShrink: 0 }}>
            <div style={{ width: 40, height: 40, borderRadius: '50%', background: 'linear-gradient(135deg,#2C5172,#112A44)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: FD, fontWeight: 800, fontSize: 15, color: '#fff', boxShadow: 'inset 0 0 0 1.5px rgba(255,255,255,0.14)' }}>M</div>
            <span style={{ position: 'absolute', bottom: 0, right: 0, width: 11, height: 11, borderRadius: '50%', background: T.green, border: '2px solid ' + T.navy }} />
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: FD, fontWeight: 800, fontSize: 16, color: '#fff', fontStretch: '110%' }}>Viamar Support</div>
            <div style={{ fontFamily: FM, fontSize: 10.5, color: 'rgba(255,255,255,0.6)' }}>Marco · agent · online</div>
          </div>
          <div style={{ width: 38, height: 38, borderRadius: 11, background: 'rgba(255,255,255,0.08)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="phone" size={18} color="#fff" stroke={1.9} />
          </div>
        </div>
        {/* context chip */}
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, marginTop: 13, background: 'rgba(255,255,255,0.07)', borderRadius: 999, padding: '6px 12px' }}>
          <Icon name="car" size={14} color={T.red} stroke={2} />
          <span style={{ fontFamily: FM, fontSize: 10.5, color: 'rgba(255,255,255,0.8)', letterSpacing: 0.3 }}>VMR-48217 · BMW M4 · in transit</span>
        </div>
      </div>

      {/* messages */}
      <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '16px 16px 8px' }}>
        {messages.map((m, i) => <Bubble key={i} m={m} />)}
        {typing && (
          <div className="m-bubble" style={{ display: 'flex', justifyContent: 'flex-start', marginBottom: 10 }}>
            <div className="m-typing" style={{ background: '#fff', border: '1px solid ' + T.line2, borderRadius: '18px 18px 18px 5px', padding: '13px 16px', boxShadow: '0 1px 2px rgba(10,27,46,0.06)' }}>
              <span></span><span></span><span></span>
            </div>
          </div>
        )}
      </div>

      {/* quick replies */}
      <div style={{ flexShrink: 0, display: 'flex', gap: 8, overflowX: 'auto', padding: '6px 16px 10px', scrollbarWidth: 'none' }}>
        {QUICK_REPLIES.map((q, i) => (
          <div key={i} onClick={() => send(q)} style={{ flexShrink: 0, background: '#fff', border: '1.5px solid ' + T.line, borderRadius: 999, padding: '9px 14px', fontFamily: FB, fontWeight: 600, fontSize: 12.5, color: T.navy, cursor: 'pointer' }}>{q}</div>
        ))}
      </div>

      {/* input bar */}
      <div style={{ flexShrink: 0, padding: '8px 14px 30px', background: '#fff', borderTop: '1px solid ' + T.line, display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ width: 38, height: 38, borderRadius: '50%', background: T.paper, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name="plus" size={20} color={T.muted} stroke={2.2} />
        </div>
        <input value={input} onChange={e => setInput(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') send(); }}
          placeholder="Message Viamar…"
          style={{ flex: 1, border: '1.5px solid ' + T.line, borderRadius: 999, padding: '11px 16px', fontSize: 14.5, color: T.ink, outline: 'none', background: T.paper }} />
        <div onClick={() => send()} style={{ width: 40, height: 40, borderRadius: '50%', background: input.trim() ? T.red : T.line, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, cursor: 'pointer', transition: 'background .15s', boxShadow: input.trim() ? '0 4px 12px rgba(221,28,36,0.3)' : 'none' }}>
          <Icon name="arrowR" size={19} color="#fff" stroke={2.4} />
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ChatScreen, smartReply });
