// Simple Pro Mobile — Belle AI Assistant Screen
const { useState, useRef, useEffect } = React;

const BELLE_QUICK_PROMPTS = [
  "What's left today?",
  "Text customer ETA",
  "Record cash payment",
  "Move job to tomorrow",
  "Turn estimate → invoice",
  "Add materials to job",
];

const INITIAL_MESSAGES = [
  { from:'belle', text:"Hi, I'm Belle. I can help you manage jobs, send messages, create invoices, and run your business. What do you need?" },
];

const BELLE_RESPONSES = {
  "what's left today?": {
    text: "You have 2 more jobs today:\n\n• **2:00 PM** — Full Bath Re-pipe, Steinberg Corp (3h)\n• **5:30 PM** — Leak Inspection, Nguyen Group (1h)\n\nYou're on track if you finish Ramos Residence by 1:30 PM.",
    actions: [{ label:'Open schedule', screen:'schedule' }, { label:'Call Steinberg', screen:null }]
  },
  "text customer eta": {
    text: 'Sure — sending to Ramos Residence:\n\n_"Hi, this is Marcus from Simple Pro Plumbing. I\'m finishing up at my current job and will be at your location around 1:30 PM. See you soon!"_\n\nSend this?',
    actions: [{ label:'Send text', screen:null }, { label:'Edit first', screen:null }]
  },
  "record cash payment": {
    text: 'Which job? I see one with an open balance:\n\n• **Drain Clog — Kitchen** — Ramos Residence — $320\n\nShall I record a $320 cash payment?',
    actions: [{ label:'Record $320 cash', screen:null }, { label:'Different amount', screen:null }]
  },
  "move job to tomorrow": {
    text: "Which job would you like to reschedule to tomorrow (Tuesday, Apr 22)?\n\n• **2:00 PM** — Full Bath Re-pipe, Steinberg Corp\n• **5:30 PM** — Leak Inspection, Nguyen Group",
    actions: [{ label:'Move Re-pipe', screen:null }, { label:'Move Inspection', screen:null }]
  },
  "turn estimate → invoice": {
    text: "I found 2 approved estimates ready to convert:\n\n• **EST-0094** — Steinberg Corp — $2,800\n• **EST-0097** — Nguyen Group — $550\n\nConvert both to invoices?",
    actions: [{ label:'Convert both', screen:null }, { label:'Choose one', screen:null }]
  },
  "add materials to job": {
    text: "Which job? I'll add materials to the job cost so it appears on the invoice.",
    actions: [{ label:'Drain Clog (active)', screen:null }, { label:'Re-pipe job', screen:null }]
  },
};

function getResponse(input) {
  const lower = input.toLowerCase().trim();
  for (const [key, val] of Object.entries(BELLE_RESPONSES)) {
    if (lower.includes(key.split(' ')[0]) || lower === key) return val;
  }
  return {
    text: `Got it. I'm working on that — _"${input}"_. Give me a moment…`,
    actions: [{ label:'Done', screen:null }]
  };
}

function BelleScreen({ onNav, params }) {
  const [messages, setMessages] = useState(INITIAL_MESSAGES);
  const [input, setInput] = useState(params?.prompt || '');
  const [thinking, setThinking] = useState(false);
  const scrollRef = useRef(null);

  useEffect(() => {
    if (params?.prompt) {
      handleSend(params.prompt);
    }
  }, []);

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

  function handleSend(text) {
    const msg = text || input;
    if (!msg.trim()) return;
    const newMsgs = [...messages, { from:'user', text: msg }];
    setMessages(newMsgs);
    setInput('');
    setThinking(true);
    setTimeout(() => {
      const resp = getResponse(msg);
      setMessages([...newMsgs, { from:'belle', text: resp.text, actions: resp.actions }]);
      setThinking(false);
    }, 900);
  }

  function renderText(text) {
    // Simple markdown: bold **x**, italic _x_, newlines
    const parts = text.split('\n').map((line, li) => {
      const segments = line.split(/(\*\*[^*]+\*\*|_[^_]+_)/g).map((seg, si) => {
        if (seg.startsWith('**') && seg.endsWith('**')) return <strong key={si}>{seg.slice(2,-2)}</strong>;
        if (seg.startsWith('_') && seg.endsWith('_')) return <em key={si}>{seg.slice(1,-1)}</em>;
        return seg;
      });
      return <div key={li} style={{marginBottom: li < text.split('\n').length-1 ? 4 : 0}}>{segments}</div>;
    });
    return parts;
  }

  return (
    <div style={{background:'#f7f7f8',minHeight:'100%',display:'flex',flexDirection:'column',height:'100%'}}>
      {/* Header */}
      <div style={{background:'#0f172a',paddingTop:56,paddingBottom:16,paddingLeft:20,paddingRight:20,
        flexShrink:0}}>
        <div style={{display:'flex',alignItems:'center',gap:12}}>
          <div style={{width:40,height:40,borderRadius:'50%',
            background:'linear-gradient(135deg,#7c3aed 0%,#4f46e5 100%)',
            display:'flex',alignItems:'center',justifyContent:'center',
            boxShadow:'0 3px 12px rgba(124,58,237,0.4)'}}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="white">
              <path d="M12 2l2.09 6.26L20 9.27l-4.91 4.73 1.18 6.88L12 17.77l-6.27 3.11 1.18-6.88L2 9.27l5.91-1.01L12 2z"/>
            </svg>
          </div>
          <div>
            <div style={{fontSize:17,fontWeight:700,color:'white',letterSpacing:'-0.015em'}}>Belle</div>
            <div style={{fontSize:12,color:'rgba(255,255,255,0.38)',fontWeight:500}}>AI Business Assistant · Always on</div>
          </div>
        </div>
      </div>

      {/* Quick prompts */}
      {messages.length <= 1 && (
        <div style={{padding:'12px 16px 4px',flexShrink:0}}>
          <div style={{fontSize:12,fontWeight:600,color:'rgba(0,0,0,0.35)',letterSpacing:'0.04em',
            textTransform:'uppercase',marginBottom:8}}>Try asking</div>
          <div style={{display:'flex',flexWrap:'wrap',gap:7}}>
            {BELLE_QUICK_PROMPTS.map(p => (
              <div key={p} onClick={() => handleSend(p)}
                style={{padding:'7px 12px',borderRadius:999,border:'1px solid rgba(124,58,237,0.25)',
                  background:'#f5f0ff',color:'#4c1d95',fontSize:13,fontWeight:500,cursor:'pointer',
                  letterSpacing:'-0.005em'}}>
                {p}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Messages */}
      <div ref={scrollRef}
        style={{flex:1,overflowY:'auto',padding:'12px 16px',display:'flex',
          flexDirection:'column',gap:10,paddingBottom:16}}>
        {messages.map((m, i) => (
          <div key={i} style={{display:'flex',flexDirection:'column',
            alignItems: m.from==='user' ? 'flex-end' : 'flex-start',gap:6}}>
            {m.from==='belle' && (
              <div style={{display:'flex',alignItems:'center',gap:5,marginBottom:1}}>
                <div style={{width:18,height:18,borderRadius:'50%',
                  background:'linear-gradient(135deg,#7c3aed,#4f46e5)',
                  display:'flex',alignItems:'center',justifyContent:'center'}}>
                  <svg width="8" height="8" viewBox="0 0 24 24" fill="white">
                    <path d="M12 2l2.09 6.26L20 9.27l-4.91 4.73 1.18 6.88L12 17.77l-6.27 3.11 1.18-6.88L2 9.27l5.91-1.01L12 2z"/>
                  </svg>
                </div>
                <span style={{fontSize:11,fontWeight:700,color:'#7c3aed',letterSpacing:'0.04em',textTransform:'uppercase'}}>Belle</span>
              </div>
            )}
            <div style={{
              maxWidth:'84%',
              padding: m.from==='user' ? '10px 14px' : '12px 14px',
              borderRadius: m.from==='user' ? '18px 18px 4px 18px' : '4px 18px 18px 18px',
              background: m.from==='user' ? '#0071e3' : 'white',
              color: m.from==='user' ? 'white' : '#111',
              fontSize:14,lineHeight:1.55,letterSpacing:'-0.005em',
              border: m.from==='belle' ? '1px solid rgba(0,0,0,0.07)' : 'none',
              boxShadow: m.from==='belle' ? '0 1px 4px rgba(0,0,0,0.05)' : 'none',
            }}>
              {renderText(m.text)}
            </div>
            {/* Action buttons */}
            {m.actions && m.actions.length > 0 && (
              <div style={{display:'flex',gap:7,flexWrap:'wrap',maxWidth:'84%'}}>
                {m.actions.map((a, ai) => (
                  <div key={ai}
                    onClick={() => { if(a.screen) onNav(a.screen); }}
                    style={{padding:'7px 14px',borderRadius:999,
                      background: ai===0 ? '#7c3aed' : 'white',
                      color: ai===0 ? 'white' : '#4c1d95',
                      border: ai===0 ? 'none' : '1px solid rgba(124,58,237,0.25)',
                      fontSize:13,fontWeight: ai===0 ? 600 : 500,cursor:'pointer'}}>
                    {a.label}
                  </div>
                ))}
              </div>
            )}
          </div>
        ))}
        {thinking && (
          <div style={{display:'flex',alignItems:'flex-start',gap:8}}>
            <div style={{padding:'12px 16px',background:'white',borderRadius:'4px 18px 18px 18px',
              border:'1px solid rgba(0,0,0,0.07)',display:'flex',gap:5,alignItems:'center'}}>
              {[0,1,2].map(i => (
                <div key={i} style={{width:7,height:7,borderRadius:'50%',background:'#7c3aed',
                  opacity:0.4,animation:`pulse 1.2s ease-in-out ${i*0.2}s infinite`}}/>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Input */}
      <div style={{padding:'10px 16px 28px',background:'white',
        borderTop:'0.5px solid rgba(0,0,0,0.08)',flexShrink:0,
        display:'flex',gap:10,alignItems:'flex-end'}}>
        <div style={{flex:1,minHeight:40,background:'#f2f2f4',borderRadius:20,
          display:'flex',alignItems:'center',padding:'0 14px'}}>
          <input
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={e => e.key==='Enter' && handleSend()}
            placeholder="Ask Belle anything…"
            style={{flex:1,border:'none',background:'transparent',fontSize:15,color:'#111',
              outline:'none',fontFamily:'inherit',letterSpacing:'-0.008em'}}/>
        </div>
        <div onClick={() => handleSend()}
          style={{width:40,height:40,borderRadius:'50%',flexShrink:0,
            background: input.trim() ? 'linear-gradient(135deg,#7c3aed,#4f46e5)' : '#e8e8ec',
            display:'flex',alignItems:'center',justifyContent:'center',cursor:'pointer',
            transition:'background 0.2s',boxShadow: input.trim() ? '0 3px 10px rgba(124,58,237,0.4)':' none'}}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill={input.trim() ? 'white' : '#999'} stroke="none">
            <line x1="22" y1="2" x2="11" y2="13" stroke={input.trim() ? 'white' : '#999'} strokeWidth="2" fill="none"/>
            <polygon points="22 2 15 22 11 13 2 9 22 2" fill={input.trim() ? 'white' : '#999'}/>
          </svg>
        </div>
      </div>

      <style>{`
        @keyframes pulse {
          0%, 100% { opacity: 0.4; transform: scale(1); }
          50%       { opacity: 1;   transform: scale(1.2); }
        }
      `}</style>
    </div>
  );
}

Object.assign(window, { BelleScreen });
