// whatsapp.jsx — WhatsApp OCR bot pentru indexuri apometre (mock conversational)

function WhatsAppScreen({ state, tr, lang }) {
  const [activeChat, setActiveChat] = React.useState('a3'); // Dumitrescu Ana — în mijloc de citire
  const [demoStep, setDemoStep] = React.useState(0);
  const toast = useToast();

  // 4 conversații demo
  const chats = [
    { aptId: 'a3', status: 'in_progress', last_at: 'acum 2 min',  preview: 'Bun, am văzut apometrul. Citire: 190.100. Confirmi?' },
    { aptId: 'a1', status: 'completed',   last_at: 'azi, 09:14',  preview: '✓ Citiri salvate. Mulțumesc!' },
    { aptId: 'a7', status: 'awaiting',    last_at: 'ieri 18:42',  preview: 'Bună ziua! Trimite-mi o poză cu apometrul...' },
    { aptId: 'a9', status: 'completed',   last_at: '12 nov, 11:30', preview: '✓ Citiri salvate. Apă rece: 270.800' },
  ];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1280 }}>
      <PageHeader
        title="WhatsApp Bot · Indexuri"
        subtitle="Locatarii trimit poza apometrului · OCR extrage cifrele · adminul nu mai introduce manual"
        right={<div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '6px 12px', borderRadius: 999, background: '#DDF0E4', color: '#065F46', fontWeight: 600, fontSize: 12 }}>
          <span style={{ width: 8, height: 8, borderRadius: 999, background: '#25D366' }} />
          Conectat · Bot Whatsapp Business
        </div>}
      />

      {/* Why this exists */}
      <Card style={{ background: 'linear-gradient(135deg, #DCFCE7, #BBF7D0)', border: '1px solid #25D366' }}>
        <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: '#25D366', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22, flexShrink: 0 }}>💬</div>
          <div style={{ flex: 1, fontSize: 13.5, color: '#14532D', lineHeight: 1.55 }}>
            <b>Realitate românească:</b> 60% dintre locatari nu vor instala niciodată o aplicație. Dar au WhatsApp deschis. Bot-ul scării primește poza apometrului → AI Vision extrage cifrele → confirmă cu locatarul. <b>~4-6 ore lunare economisite</b> pentru admin. Funcționează și pentru bunica de 78 ani.
          </div>
        </div>
      </Card>

      {/* Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 'var(--gap)' }}>
        <SummaryCard icon="phone" iconBg="#DCFCE7" iconColor="#15803D" label="Locatari conectați" value="11 / 12" sub="92% pe WhatsApp" />
        <SummaryCard icon="check" iconBg="#DDF0E4" iconColor="#065F46" label="Citiri OCR luna asta" value="9 / 12" sub="3 în așteptare" />
        <SummaryCard icon="sparkles" iconBg="#FEF3C7" iconColor="#92400E" label="Acuratețe OCR" value="97.4%" sub="2 corectate manual" />
        <SummaryCard icon="clock" iconBg="#E0F2FE" iconColor="#0369A1" label="Timp economisit" value="~5.2h" sub="vs. introducere manuală" />
      </div>

      {/* Layout: chat list + conversation */}
      <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr', gap: 'var(--gap)', minHeight: 600 }}>
        {/* Chat list */}
        <Card padded={false}>
          <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)' }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>Conversații</div>
          </div>
          {chats.map(c => {
            const apt = state.apartments.find(a => a.id === c.aptId);
            const active = activeChat === c.aptId;
            return (
              <button key={c.aptId} onClick={() => setActiveChat(c.aptId)} style={{
                width: '100%', padding: '14px 18px',
                background: active ? 'var(--surface-2)' : 'transparent',
                border: 0, borderBottom: '1px solid var(--border)', cursor: 'pointer',
                borderLeft: active ? '3px solid var(--primary)' : '3px solid transparent',
                fontFamily: 'inherit', textAlign: 'left',
                display: 'flex', alignItems: 'center', gap: 12,
              }}>
                <div style={{
                  width: 40, height: 40, borderRadius: 999,
                  background: c.status === 'completed' ? '#25D366' : c.status === 'in_progress' ? '#F59E0B' : 'var(--muted)', color: '#fff',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontWeight: 700, fontSize: 13,
                }}>{apt?.owner_name.split(' ').map(p => p[0]).join('').slice(0, 2)}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
                    <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{apt?.owner_name}</span>
                    <span style={{ fontSize: 10, color: 'var(--muted)', whiteSpace: 'nowrap' }}>{c.last_at}</span>
                  </div>
                  <div style={{ fontSize: 11.5, color: 'var(--muted)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', marginTop: 2 }}>
                    {c.preview}
                  </div>
                </div>
              </button>
            );
          })}
        </Card>

        {/* Conversation */}
        <Card padded={false} style={{ display: 'flex', flexDirection: 'column' }}>
          <WhatsAppConversation aptId={activeChat} state={state} demoStep={demoStep} setDemoStep={setDemoStep} />
        </Card>
      </div>
    </div>
  );
}

function WhatsAppConversation({ aptId, state, demoStep, setDemoStep }) {
  const apt = state.apartments.find(a => a.id === aptId);
  const r = state.readings[aptId];

  // Build conversation messages based on apt and step
  const messages = React.useMemo(() => {
    const base = [
      { from: 'bot', text: `Bună ziua, ${apt.owner_name.split(' ')[1]}! 👋\n\nE timpul pentru indexurile apometrelor pe luna noiembrie. Te rog trimite o poză cu fiecare apometru (apă rece și apă caldă).`, ts: '14:02' },
      { from: 'tenant', text: 'Bună! Dau acum.', ts: '14:03' },
    ];
    if (aptId === 'a3') {
      // Ana - in middle of OCR confirmation
      base.push(
        { from: 'tenant', type: 'image', caption: 'Apă rece', ts: '14:08', mockImage: '💧 Apometru apă rece — Itron 23.5' },
        { from: 'bot', text: '✨ Văd cifrele:\n\n💧 **Apă rece: 190.100 m³**\n\nE corect? Trimite "DA" sau corectează manual.', ts: '14:08', highlight: true },
        ...(demoStep >= 1 ? [
          { from: 'tenant', text: 'DA', ts: '14:09' },
          { from: 'bot', text: '✅ Citire salvată. Mulțumesc!\n\nMai am nevoie de citirea de la apă caldă. Trimite o poză.', ts: '14:09' },
        ] : []),
        ...(demoStep >= 2 ? [
          { from: 'tenant', type: 'image', caption: 'Apă caldă', ts: '14:11', mockImage: '🚿 Apometru apă caldă — Itron 18.2' },
          { from: 'bot', text: '✨ Văd cifrele:\n\n🚿 **Apă caldă: 78.100 m³**\n\nE corect?', ts: '14:11', highlight: true },
        ] : []),
        ...(demoStep >= 3 ? [
          { from: 'tenant', text: 'Da, mulțumesc', ts: '14:12' },
          { from: 'bot', text: '✅ Toate citirile salvate!\n\n📊 Consum noiembrie:\n💧 Apă rece: 1.6 m³ → ~20 RON\n🚿 Apă caldă: 0.9 m³ → ~34 RON\n\nLista de plată completă vine pe 25 nov.', ts: '14:13' },
        ] : []),
      );
    } else if (aptId === 'a1') {
      base.push(
        { from: 'tenant', type: 'image', caption: 'Apometre', ts: '09:11', mockImage: '💧 Apometru Itron' },
        { from: 'bot', text: '✨ Văd cifrele:\n\n💧 Apă rece: 237.840 m³\n🚿 Apă caldă: 91.200 m³\n\nE corect?', ts: '09:12' },
        { from: 'tenant', text: 'Da', ts: '09:13' },
        { from: 'bot', text: '✅ Citiri salvate. Mulțumesc!', ts: '09:14' },
      );
    } else if (aptId === 'a7') {
      base.push(
        { from: 'tenant', text: 'OK, fac mâine dimineață', ts: 'ieri 18:42' },
        { from: 'bot', text: '👍 Te aștept. Nu uita că termenul e 20 nov.', ts: 'ieri 18:42' },
      );
    } else if (aptId === 'a9') {
      base.push(
        { from: 'tenant', type: 'image', caption: 'Citiri', ts: '11:28', mockImage: '💧🚿 Apometre' },
        { from: 'bot', text: '✨ Văd cifrele:\n\n💧 Apă rece: 270.800 m³\n🚿 Apă caldă: 104.200 m³', ts: '11:29' },
        { from: 'tenant', text: 'corect', ts: '11:30' },
        { from: 'bot', text: '✅ Citiri salvate. Mulțumesc, doamna Andreea!', ts: '11:30' },
      );
    }
    return base;
  }, [aptId, demoStep, apt, r]);

  return (
    <>
      {/* Header */}
      <div style={{
        padding: '14px 18px', borderBottom: '1px solid var(--border)',
        background: '#075E54', color: '#fff',
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <div style={{
          width: 40, height: 40, borderRadius: 999,
          background: '#128C7E', color: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontWeight: 700, fontSize: 14,
        }}>{apt.owner_name.split(' ').map(p => p[0]).join('').slice(0, 2)}</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14, fontWeight: 600 }}>{apt.owner_name}</div>
          <div style={{ fontSize: 11, opacity: 0.8 }}>Ap. {apt.number} · {apt.owner_phone}</div>
        </div>
        <div style={{ fontSize: 11, padding: '3px 8px', borderRadius: 999, background: 'rgba(255,255,255,0.18)', fontWeight: 600 }}>
          🤖 BlocApp Bot
        </div>
      </div>

      {/* Messages */}
      <div style={{
        flex: 1, padding: '20px 18px', overflowY: 'auto',
        background: 'repeating-linear-gradient(135deg, #ECE5DD, #ECE5DD 6px, #E8E0D5 6px, #E8E0D5 12px)',
        display: 'flex', flexDirection: 'column', gap: 8,
      }}>
        {messages.map((m, i) => (
          <WaMessage key={i} m={m} />
        ))}
      </div>

      {/* Demo controls */}
      {aptId === 'a3' && (
        <div style={{ padding: '14px 18px', borderTop: '1px solid var(--border)', background: 'var(--surface-2)', display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ flex: 1, fontSize: 12, color: 'var(--muted)' }}>
            <b>Demo</b> — apasă pentru a derula conversația
          </div>
          {demoStep < 3 && <Button size="sm" variant="primary" onClick={() => setDemoStep(s => s + 1)}>Următorul pas →</Button>}
          {demoStep === 3 && <Button size="sm" variant="secondary" onClick={() => setDemoStep(0)}>Reia demo</Button>}
        </div>
      )}
    </>
  );
}

function WaMessage({ m }) {
  const isBot = m.from === 'bot';
  return (
    <div style={{ display: 'flex', justifyContent: isBot ? 'flex-start' : 'flex-end' }}>
      <div style={{
        maxWidth: '75%', padding: '8px 12px',
        background: isBot ? '#fff' : '#DCF8C6',
        borderRadius: 8,
        borderTopLeftRadius: isBot ? 2 : 8,
        borderTopRightRadius: isBot ? 8 : 2,
        boxShadow: '0 1px 0.5px rgba(0,0,0,0.13)',
        fontSize: 13.5, color: '#111B21', lineHeight: 1.45,
        position: 'relative',
      }}>
        {m.type === 'image' && (
          <div style={{
            margin: '-3px -6px 6px', padding: '40px 14px',
            background: 'linear-gradient(135deg, #cbd5e1, #94a3b8)', color: '#fff',
            borderRadius: 6, fontFamily: 'var(--font-mono)', fontSize: 11.5,
            textAlign: 'center', position: 'relative', minHeight: 100,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>{m.mockImage}</div>
        )}
        {m.caption && <div style={{ fontSize: 11, color: '#667781', marginBottom: 4 }}>{m.caption}</div>}
        {m.text && <div style={{ whiteSpace: 'pre-wrap' }} dangerouslySetInnerHTML={{ __html: m.text.replace(/\*\*(.+?)\*\*/g, '<b>$1</b>') }} />}
        <div style={{ fontSize: 10, color: '#667781', textAlign: 'right', marginTop: 4 }}>
          {m.ts} {!isBot && '✓✓'}
        </div>
        {m.highlight && (
          <div style={{
            position: 'absolute', top: -6, right: -6,
            padding: '2px 7px', borderRadius: 999,
            background: '#F59E0B', color: '#fff',
            fontSize: 9, fontWeight: 700, letterSpacing: '0.04em',
          }}>AI</div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { WhatsAppScreen });
