// Priya support chat — appears when the user clicks "Chat" in the sidebar
// PriyaCard. Roo "checks out" via a system message, Priya "checks in"
// and answers a small set of scripted prompts. The user can type into
// the composer and Priya replies after a short typing delay.

const PRIYA_PROMPTS = [
  { q: "What's included in the migration?",
    a: "I do the migration myself end-to-end — DB dump, file sync, DNS cutover with a low TTL, plus a 7-day rollback snapshot. Zero downtime in 99% of cases, and you stay on the old host until I confirm the new one renders identically." },
  { q: "Can I get a discount on a 3-year term?",
    a: "The 3-year price is already locked at 47% off list — that's our biggest published discount. If you're moving 3+ sites in we can talk volume; happy to put numbers together if you want." },
  { q: "Do you have a phone number I can call?",
    a: "Yep — +61 2 8014 6700 (Sydney, 9am–6pm AEST). For after-hours urgent issues my mobile is on file in the dashboard once you sign up." },
  { q: "What happens if I don't like it?",
    a: "30-day money-back, no questions. Trial doesn't auto-bill — you confirm before the first charge. If you migrate in and decide to leave, we'll move you back to your previous host for free." },
];

function PriyaChat({ userName, onClose }) {
  // Phase machine:
  //   'ask-name'  → Priya asks for the user's name, prompts hidden
  //   'open'      → name known, regular chat with suggestion prompts
  const initialName = (userName || '').trim();
  const [phase, setPhase] = React.useState(initialName ? 'open' : 'ask-name');
  const [name, setName] = React.useState(initialName);
  const [messages, setMessages] = React.useState(() => {
    if (initialName) {
      return [
        { from: 'system', text: 'Roo has handed you over to Priya.' },
        { from: 'priya', text: `Hi ${initialName} — Priya here. I run migrations and onboarding from our Sydney office. What's on your mind?` },
      ];
    }
    return [
      { from: 'system', text: 'Roo has handed you over to Priya.' },
      { from: 'priya', text: `Hi! I'm Priya, I run migrations and onboarding from our Sydney office. Before we get into it — what should I call you?` },
    ];
  });
  const [input, setInput] = React.useState('');
  const [priyaTyping, setPriyaTyping] = React.useState(false);
  const threadRef = React.useRef(null);
  const inputRef = React.useRef(null);

  // Auto-scroll to bottom on new messages or typing change
  React.useEffect(() => {
    const el = threadRef.current;
    if (el) el.scrollTo({ top: el.scrollHeight, behavior: 'smooth' });
  }, [messages, priyaTyping]);

  // Focus the input when Priya finishes typing
  React.useEffect(() => {
    if (!priyaTyping) inputRef.current?.focus();
  }, [priyaTyping]);

  const priyaSay = (text, after) => {
    setPriyaTyping(true);
    const delay = 700 + text.length * 14;
    setTimeout(() => {
      setMessages(m => [...m, { from: 'priya', text }]);
      setPriyaTyping(false);
      if (after) after();
    }, delay);
  };

  const sendUser = (text) => {
    const trimmed = text.trim();
    if (!trimmed) return;
    setMessages(m => [...m, { from: 'user', text: trimmed }]);
    setInput('');

    if (phase === 'ask-name') {
      // Extract a first name from the response. Handles "Adam", "I'm Adam",
      // "my name is Adam", "Adam Smith" — take the last capitalised word
      // or fall back to the whole input cleaned up.
      const clean = trimmed.replace(/[.!?]+$/, '').trim();
      const tokens = clean.split(/\s+/);
      const fillers = new Set(['i', "i'm", 'im', 'my', 'name', 'is', "it's", 'its', 'this', 'call', 'me']);
      const candidate = tokens.filter(t => !fillers.has(t.toLowerCase())).pop() || tokens[0] || 'there';
      const newName = candidate.charAt(0).toUpperCase() + candidate.slice(1).toLowerCase();
      setName(newName);
      setPhase('open');
      priyaSay(`Nice to meet you, ${newName}. What's on your mind?`);
      return;
    }

    // Normal Q&A
    setUserAskedSomething(true);
    const match = PRIYA_PROMPTS.find(p => trimmed.toLowerCase().includes(p.q.toLowerCase().slice(0, 10)));
    const reply = match
      ? match.a
      : "Good question — let me grab the exact numbers and come back to you. Want me to email the answer too?";
    priyaSay(reply);
  };

  const onKey = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendUser(input);
    }
  };

  // Tracks whether the user has asked a "real" question (anything sent
  // after the name exchange). Suggestion prompts show until first such
  // message arrives.
  const [userAskedSomething, setUserAskedSomething] = React.useState(false);
  const showPrompts = phase === 'open' && !userAskedSomething && !priyaTyping;

  return (
    <>
      <div className="sc-thread" ref={threadRef} style={{background:'#fff'}}>
        {messages.map((m, i) => {
          if (m.from === 'system') {
            return <div key={i} className="sc-system" style={{margin:'8px 0'}}>{m.text}</div>;
          }
          if (m.from === 'priya') {
            return (
              <div key={i} className="sc-msg sc-msg-fade-in">
                <div className="sc-avatar" style={{background:'linear-gradient(135deg, #4B8DFF, #0C1A57)', color:'#fff', fontSize:11, fontWeight:600}}>PS</div>
                <div className="sc-msg-body">
                  <div className="sc-msg-name">Priya<span className="role">Specialist · Sydney</span></div>
                  <div className="sc-msg-text">{m.text}</div>
                </div>
              </div>
            );
          }
          // user
          return (
            <div key={i} className="sc-user sc-msg-fade-in" style={{maxWidth:'70%', alignSelf:'flex-end', marginLeft:'auto', background:'var(--midnight)', color:'#fff', padding:'10px 14px', borderRadius:'14px 14px 4px 14px', fontSize:14, lineHeight:1.5}}>
              {m.text}
            </div>
          );
        })}
        {priyaTyping && (
          <div className="sc-msg sc-msg-fade-in">
            <div className="sc-avatar" style={{background:'linear-gradient(135deg, #4B8DFF, #0C1A57)', color:'#fff', fontSize:11, fontWeight:600}}>PS</div>
            <div className="sc-msg-body">
              <div className="sc-msg-name">Priya<span className="role">Specialist · Sydney</span></div>
              <div className="sc-typing-bubble" style={{marginTop:4}}>
                <div className="sc-typing-dots"><span /><span /><span /></div>
              </div>
            </div>
          </div>
        )}
        {showPrompts && (
          <div style={{display:'flex', flexWrap:'wrap', gap:6, marginTop:8, marginLeft:48}}>
            {PRIYA_PROMPTS.map((p, i) => (
              <button
                key={i}
                className="btn btn-ghost"
                onClick={() => sendUser(p.q)}
                style={{fontSize:12.5, padding:'6px 12px'}}
              >
                {p.q}
              </button>
            ))}
          </div>
        )}
      </div>
      <div className="sc-composer" style={{padding:'14px 24px'}}>
        <div style={{display:'flex', gap:10, alignItems:'center'}}>
          <input
            ref={inputRef}
            className="sc-input"
            placeholder={phase === 'ask-name' ? 'Type your name…' : 'Type a message to Priya…'}
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={onKey}
            style={{flex:1, padding:'12px 14px', minWidth:0}}
          />
          <button
            className="btn btn-primary"
            onClick={() => sendUser(input)}
            disabled={!input.trim()}
            style={{padding:'12px 16px', flex:'0 0 auto', opacity: input.trim() ? 1 : 0.55, cursor: input.trim() ? 'pointer' : 'default'}}
          >
            <Icon name="send" size={14} />
          </button>
        </div>
        <div style={{marginTop:8, display:'flex', justifyContent:'space-between', alignItems:'center', gap:12, flexWrap:'wrap'}}>
          <span style={{fontSize:11.5, color:'var(--gray-500)'}}>
            Chatting with a real human in our Sydney office · Replies in ~6 min
          </span>
          <button
            onClick={onClose}
            style={{background:'transparent', border:'none', padding:0, fontSize:12, color:'var(--gray-700)', cursor:'pointer', textDecoration:'underline'}}
          >
            End chat → back to Roo
          </button>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { PriyaChat });
