// app.jsx — Product app: shell, dashboard, conversations, reservations, knowledge, channels
const { useState, useEffect, useRef, useMemo } = React;

// ─────── Sidebar ───────

const NAV_ITEMS = [
  { id: 'dashboard',     to: '/dashboard',      label: 'Dashboard',      icon: 'chart' },
  { id: 'conversations', to: '/conversations',  label: 'Conversations',  icon: 'message',  count: 12 },
  { id: 'reservations',  to: '/reservations',   label: 'Reservations',   icon: 'calendar', count: 4 },
  { id: 'knowledge',     to: '/knowledge',      label: 'Knowledge base', icon: 'book' },
  { id: 'channels',      to: '/channels',       label: 'Channels',       icon: 'plug' },
  { id: 'analytics',     to: '/dashboard',      label: 'Analytics',      icon: 'layers' },
  { id: 'team',          to: '/dashboard',      label: 'Team',           icon: 'users' },
];

function Sidebar({ active }) {
  return (
    <aside className="sidebar">
      <div className="sidebar-section" style={{ borderBottom: '1px solid var(--border)' }}>
        <Logo/>
      </div>

      {/* workspace switcher */}
      <div style={{ padding: 12, borderBottom: '1px solid var(--border)' }}>
        <div className="card hoverable" style={{ padding: 8, display: 'flex', alignItems: 'center', gap: 8, background: 'var(--bg-2)' }}>
          <div className="avatar" style={{ width: 28, height: 28, fontSize: 11, background: 'linear-gradient(135deg,#10B981,#059669)', borderRadius: 7 }}>TV</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12.5, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Trattoria Volta</div>
            <div className="dim" style={{ fontSize: 10.5 }}>Pro plan · Milan</div>
          </div>
          <Icons.arrowDown size={12} stroke="var(--text-3)"/>
        </div>
      </div>

      <div className="sidebar-section" style={{ flex: 1, gap: 2, display: 'flex', flexDirection: 'column' }}>
        {NAV_ITEMS.map(item => {
          const Ic = Icons[item.icon];
          const isActive = active === item.id;
          return (
            <Link key={item.id} to={item.to} className={'sidebar-item' + (isActive ? ' active' : '')}>
              <Ic size={15}/>
              <span style={{ flex: 1 }}>{item.label}</span>
              {item.count != null && <span style={{ fontSize: 10, color: isActive ? 'var(--accent)' : 'var(--text-3)', fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>{item.count}</span>}
            </Link>
          );
        })}
      </div>

      {/* AI usage */}
      <div className="sidebar-section" style={{ borderTop: '1px solid var(--border)' }}>
        <div style={{ padding: '4px 6px 8px' }}>
          <div className="row" style={{ justifyContent: 'space-between', marginBottom: 6 }}>
            <span style={{ fontSize: 11, color: 'var(--text-2)' }}>AI replies this month</span>
          </div>
          <div className="row gap-2" style={{ marginBottom: 8 }}>
            <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-0)' }}>4,128</span>
            <span style={{ fontSize: 11, color: 'var(--text-3)' }}>· unlimited</span>
          </div>
          <div style={{ height: 4, background: 'var(--bg-2)', borderRadius: 2, overflow: 'hidden' }}>
            <div style={{ width: '38%', height: '100%', background: 'linear-gradient(90deg, #10B981, #34D399)', borderRadius: 2, boxShadow: '0 0 8px rgba(16,185,129,0.5)' }}/>
          </div>
        </div>
      </div>

      {/* user */}
      <div style={{ padding: 12, borderTop: '1px solid var(--border)', display: 'flex', gap: 10, alignItems: 'center' }}>
        <div className="avatar" style={{ width: 32, height: 32, background: 'linear-gradient(135deg, #ec4899, #8b5cf6)', fontSize: 12 }}>EM</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 12.5, fontWeight: 500 }}>Elena Marchetti</div>
          <div className="dim" style={{ fontSize: 11 }}>elena@volta.com</div>
        </div>
        <button style={{ appearance: 'none', border: 0, background: 'transparent', color: 'var(--text-3)', padding: 4, borderRadius: 6, cursor: 'default' }}>
          <Icons.settings size={14}/>
        </button>
      </div>
    </aside>
  );
}

// ─────── App top bar ───────

function AppTopbar({ title, action }) {
  return (
    <div style={{
      padding: '16px 32px',
      borderBottom: '1px solid var(--border)',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      background: 'rgba(10,10,12,0.6)',
      backdropFilter: 'blur(12px)',
      position: 'sticky', top: 0, zIndex: 4,
    }}>
      <div className="row gap-3" style={{ flex: 1 }}>
        <h3 style={{ fontSize: 18, fontWeight: 600, margin: 0 }}>{title}</h3>
        <div style={{ position: 'relative', flex: 1, maxWidth: 320, marginLeft: 24 }}>
          <Icons.search size={14} style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-3)' }}/>
          <input className="input" style={{ height: 36, paddingLeft: 36, fontSize: 13 }} placeholder="Search messages, customers, reservations..."/>
          <span style={{ position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)', fontSize: 11, color: 'var(--text-3)', padding: '2px 6px', border: '1px solid var(--border)', borderRadius: 4 }}>⌘K</span>
        </div>
      </div>
      <div className="row gap-2">
        {action}
        <button className="btn btn-ghost btn-sm"><Icons.bell size={14}/></button>
        <button className="btn btn-primary btn-sm"><Icons.plus size={13}/> New</button>
      </div>
    </div>
  );
}

// ─────── DASHBOARD ───────

function StatCard({ label, num, delta, deltaDir = 'up', icon: Ic, color = 'emerald' }) {
  return (
    <div className="card stat-card hoverable">
      <div className="row" style={{ justifyContent: 'space-between' }}>
        <span className="muted" style={{ fontSize: 12 }}>{label}</span>
        <div style={{
          width: 28, height: 28, borderRadius: 7,
          background: color === 'emerald' ? 'rgba(16,185,129,0.1)' : color === 'blue' ? 'rgba(59,130,246,0.1)' : color === 'amber' ? 'rgba(245,158,11,0.1)' : 'rgba(139,92,246,0.1)',
          color: color === 'emerald' ? 'var(--accent)' : color === 'blue' ? 'var(--info)' : color === 'amber' ? 'var(--warn)' : '#8B5CF6',
          display:'flex', alignItems:'center', justifyContent:'center',
        }}>
          <Ic size={14}/>
        </div>
      </div>
      <div className="stat-num">{num}</div>
      <div className="row gap-2">
        <span className={'stat-delta ' + (deltaDir === 'down' ? 'down' : '')}>
          {deltaDir === 'up' ? '↑' : '↓'} {delta}
        </span>
        <span className="dim" style={{ fontSize: 11 }}>vs. last week</span>
      </div>
    </div>
  );
}

function MiniChart({ data, color = 'var(--accent)' }) {
  const max = Math.max(...data);
  const min = Math.min(...data);
  const range = max - min || 1;
  const w = 100, h = 100;
  const pts = data.map((v, i) => `${(i/(data.length-1))*w},${h - ((v-min)/range)*h*0.85 - h*0.075}`).join(' ');
  const area = `0,${h} ${pts} ${w},${h}`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ width: '100%', height: '100%' }}>
      <defs>
        <linearGradient id="chart-grad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.4"/>
          <stop offset="100%" stopColor={color} stopOpacity="0"/>
        </linearGradient>
      </defs>
      <polygon points={area} fill="url(#chart-grad)"/>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" vectorEffect="non-scaling-stroke" style={{ filter: 'drop-shadow(0 0 4px ' + color + ')' }}/>
    </svg>
  );
}

function VolumeChart() {
  const days = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
  const data = [142, 168, 195, 174, 232, 318, 287];
  const max = 350;
  const w = 720, h = 220;
  const stepX = w / (data.length - 1);
  const pts = data.map((v, i) => `${i * stepX},${h - (v / max) * h * 0.85 - 16}`).join(' ');
  const area = `0,${h} ${pts} ${w},${h}`;
  // also AI-handled portion
  const ai = data.map(v => Math.round(v * 0.94));
  const aiPts = ai.map((v, i) => `${i * stepX},${h - (v / max) * h * 0.85 - 16}`).join(' ');

  return (
    <div className="card" style={{ padding: 24, gridColumn: '1 / -1', display: 'flex', flexDirection: 'column' }}>
      <div className="row" style={{ justifyContent: 'space-between', marginBottom: 16 }}>
        <div>
          <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 2 }}>Message volume</div>
          <div className="muted" style={{ fontSize: 12 }}>Last 7 days · all channels</div>
        </div>
        <div className="row gap-3" style={{ fontSize: 12 }}>
          <span className="row gap-2"><span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--accent)' }}/>Total</span>
          <span className="row gap-2"><span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--info)' }}/>AI handled</span>
        </div>
        <div className="row gap-2">
          {['7D','30D','90D'].map(t => (
            <button key={t} className="btn btn-sm" style={{
              background: t === '7D' ? 'rgba(255,255,255,0.06)' : 'transparent',
              color: t === '7D' ? 'var(--text-0)' : 'var(--text-3)',
              border: 0,
            }}>{t}</button>
          ))}
        </div>
      </div>
      <svg viewBox={`0 0 ${w} ${h}`} style={{ width: '100%', height: 160 }} preserveAspectRatio="none">
        <defs>
          <linearGradient id="vol-grad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#10B981" stopOpacity="0.32"/>
            <stop offset="100%" stopColor="#10B981" stopOpacity="0"/>
          </linearGradient>
          <linearGradient id="ai-grad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#3B82F6" stopOpacity="0.16"/>
            <stop offset="100%" stopColor="#3B82F6" stopOpacity="0"/>
          </linearGradient>
        </defs>
        <polygon points={area} fill="url(#vol-grad)"/>
        <polyline points={pts} fill="none" stroke="#10B981" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ filter: 'drop-shadow(0 0 6px rgba(16,185,129,0.5))' }}/>
        <polyline points={aiPts} fill="none" stroke="#3B82F6" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" strokeDasharray="3 3" opacity="0.7"/>
        {/* dots */}
        {data.map((v, i) => (
          <circle key={i} cx={i * stepX} cy={h - (v / max) * h * 0.85 - 16} r="3" fill="#10B981" stroke="var(--bg-1)" strokeWidth="2"/>
        ))}
      </svg>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 12, fontSize: 11, color: 'var(--text-3)' }}>
        {days.map((d, i) => <span key={d}>{d} · {data[i]}</span>)}
      </div>
    </div>
  );
}

function RecentConvos() {
  const convos = [
    { name: 'Sofia Marchetti', ch: 'whatsapp', preview: 'Confirmed — Saturday 9 PM, table for 4', time: '2m', status: 'AI', resolved: true },
    { name: 'Marco Rossi',     ch: 'instagram', preview: 'Yes, we have gluten-free pasta options...', time: '8m', status: 'AI', resolved: true },
    { name: 'Ana Pereira',     ch: 'email',     preview: 'Hello, I need help with last night\'s receipt', time: '14m', status: 'human', resolved: false },
    { name: 'Chen Liu',        ch: 'whatsapp', preview: 'Tomorrow 7:30 for 3? — confirmed!', time: '22m', status: 'AI', resolved: true },
    { name: 'Pierre Dubois',   ch: 'facebook',  preview: 'Bonjour, êtes-vous ouverts dimanche?', time: '34m', status: 'AI', resolved: true },
    { name: 'Emma Stone',      ch: 'instagram', preview: 'Could I move my Saturday booking to...', time: '1h', status: 'AI', resolved: true },
  ];
  return (
    <div className="card" style={{ padding: 24 }}>
      <div className="row" style={{ justifyContent: 'space-between', marginBottom: 16 }}>
        <div>
          <div style={{ fontSize: 14, fontWeight: 500 }}>Recent conversations</div>
          <div className="muted" style={{ fontSize: 12 }}>Last 6 messages</div>
        </div>
        <Link to="/conversations" style={{ fontSize: 12, color: 'var(--accent)', textDecoration: 'none' }}>View all →</Link>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        {convos.map((c, i) => {
          const Ic = Icons[c.ch];
          return (
            <Link to="/conversations" key={i} className="row gap-3" style={{
              padding: '12px 0',
              borderTop: i > 0 ? '1px solid var(--border)' : 'none',
              textDecoration: 'none', color: 'inherit',
              cursor: 'default',
            }}>
              <div className={'avatar ch-' + c.ch} style={{ width: 32, height: 32 }}><Ic size={14}/></div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="row" style={{ justifyContent: 'space-between', marginBottom: 2 }}>
                  <span style={{ fontSize: 13, fontWeight: 500 }}>{c.name}</span>
                  <span className="dim" style={{ fontSize: 11 }}>{c.time}</span>
                </div>
                <div className="muted" style={{ fontSize: 12, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{c.preview}</div>
              </div>
              <span className={'badge ' + (c.status === 'AI' ? 'badge-emerald' : 'badge-blue')} style={{ fontSize: 10 }}>
                {c.status === 'AI' ? <><Icons.spark size={9}/> AI</> : <><Icons.user size={9}/> Human</>}
              </span>
            </Link>
          );
        })}
      </div>
    </div>
  );
}

function TodaysReservations() {
  const res = [
    { time: '6:30 PM', name: 'Galimberti family', size: 4, ch: 'whatsapp', status: 'confirmed' },
    { time: '7:00 PM', name: 'Riccardo Bianchi', size: 2, ch: 'instagram', status: 'confirmed' },
    { time: '7:45 PM', name: 'Group · Anniversary', size: 8, ch: 'email', status: 'pending' },
    { time: '8:30 PM', name: 'Sofia M.', size: 4, ch: 'whatsapp', status: 'confirmed' },
    { time: '9:15 PM', name: 'Walk-in expected', size: 3, ch: 'website', status: 'tentative' },
  ];
  return (
    <div className="card" style={{ padding: 24 }}>
      <div className="row" style={{ justifyContent: 'space-between', marginBottom: 16 }}>
        <div>
          <div style={{ fontSize: 14, fontWeight: 500 }}>Today's bookings</div>
          <div className="muted" style={{ fontSize: 12 }}>Tuesday · 21 covers</div>
        </div>
        <Link to="/reservations" style={{ fontSize: 12, color: 'var(--accent)', textDecoration: 'none' }}>Calendar →</Link>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        {res.map((r, i) => {
          const Ic = Icons[r.ch];
          const sBadge = r.status === 'confirmed' ? 'badge-emerald' : r.status === 'pending' ? 'badge-amber' : 'badge-blue';
          return (
            <div key={i} className="row gap-3" style={{ padding: '12px 0', borderTop: i > 0 ? '1px solid var(--border)' : 'none' }}>
              <div className="mono" style={{ fontSize: 12, fontWeight: 600, width: 64, color: 'var(--text-1)' }}>{r.time}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{r.name}</div>
                <div className="muted" style={{ fontSize: 11, display: 'flex', gap: 6, alignItems: 'center' }}>
                  <Icons.users size={10}/> {r.size} · <Ic size={10}/> {r.ch}
                </div>
              </div>
              <span className={'badge ' + sBadge} style={{ fontSize: 10 }}>{r.status}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function DashboardPage() {
  return (
    <AppShell active="dashboard">
      <AppTopbar title="Dashboard" action={
        <button className="btn btn-ghost btn-sm"><Icons.calendar size={13}/> Today</button>
      }/>
      <div style={{ padding: 32, display: 'flex', flexDirection: 'column', gap: 16 }}>
        {/* hero greeting */}
        <Reveal>
          <div className="card" style={{ padding: 24, position: 'relative', overflow: 'hidden' }}>
            <div style={{
              position: 'absolute', top: -80, right: -80, width: 320, height: 320, borderRadius: '50%',
              background: 'radial-gradient(circle, rgba(16,185,129,0.18), transparent 70%)',
              filter: 'blur(40px)', pointerEvents: 'none',
            }}/>
            <div style={{ position: 'relative' }}>
              <div className="row gap-2" style={{ marginBottom: 8 }}>
                <span className="tag"><span className="tag-dot"/>AI is online · responding in 0.6s avg</span>
              </div>
              <h2 style={{ fontSize: 24, marginBottom: 6 }}>Good evening, Elena.</h2>
              <p className="muted" style={{ margin: 0, fontSize: 14 }}>
                ReplyFlow handled <strong style={{ color: 'var(--text-0)' }}>247 messages</strong> today and booked <strong style={{ color: 'var(--accent)' }}>14 reservations</strong>. 4 conversations need your attention.
              </p>
            </div>
          </div>
        </Reveal>

        {/* stats row */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
          <StatCard label="Messages today"     num="247"   delta="12%" icon={Icons.message}  color="emerald"/>
          <StatCard label="AI resolution rate" num="98.6%" delta="2.1%" icon={Icons.spark}    color="blue"/>
          <StatCard label="New customers"      num="38"    delta="18%" icon={Icons.users}    color="violet"/>
          <StatCard label="Reservations today" num="21"    delta="5%"  icon={Icons.calendar} color="amber"/>
        </div>

        {/* main row — chart + insights + bookings */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr', gap: 16 }}>
          <VolumeChart/>
          <div className="card" style={{ padding: 24 }}>
            <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 4 }}>AI insights</div>
            <div className="muted" style={{ fontSize: 12, marginBottom: 20 }}>What guests asked this week</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {[
                { label: 'Reservations',     pct: 64, color: 'var(--accent)' },
                { label: 'Menu & dietary',   pct: 18, color: 'var(--info)' },
                { label: 'Hours & location', pct: 11, color: '#F59E0B' },
                { label: 'Receipts/support', pct: 7,  color: '#8B5CF6' },
              ].map((x, i) => (
                <div key={i}>
                  <div className="row" style={{ justifyContent: 'space-between', marginBottom: 6, fontSize: 12 }}>
                    <span style={{ color: 'var(--text-1)' }}>{x.label}</span>
                    <span className="mono" style={{ color: 'var(--text-2)' }}>{x.pct}%</span>
                  </div>
                  <div style={{ height: 4, background: 'var(--bg-2)', borderRadius: 2, overflow: 'hidden' }}>
                    <div style={{ width: x.pct + '%', height: '100%', background: x.color, borderRadius: 2 }}/>
                  </div>
                </div>
              ))}
            </div>
            <div style={{ marginTop: 20, padding: 12, background: 'rgba(245,158,11,0.06)', border: '1px solid rgba(245,158,11,0.2)', borderRadius: 8 }}>
              <div style={{ fontSize: 11, color: 'var(--warn)', fontWeight: 600, marginBottom: 4 }}>⚠ Recurring question</div>
              <div style={{ fontSize: 12 }}>5 guests asked about kids' menu. Add to knowledge base?</div>
            </div>
          </div>
          <TodaysReservations/>
        </div>

        {/* recent conversations */}
        <RecentConvos/>
      </div>
    </AppShell>
  );
}

// ─────── App shell wrapper ───────

function AppShell({ active, children }) {
  return (
    <div className="app-shell">
      <Sidebar active={active}/>
      <main style={{ minWidth: 0 }}>{children}</main>
    </div>
  );
}
window.AppShell = AppShell;

// ─────── CONVERSATIONS ───────

const CONVOS = [
  { id: 1, name: 'Sofia Marchetti', ch: 'whatsapp', avatar: 'SM', status: 'AI', unread: 0, time: '2m',
    preview: "Saturday 9 PM, party of 4 — confirmed",
    messages: [
      { from: 'them', text: 'Hi! Table for 4 tonight at 8?', time: '8:42 PM' },
      { from: 'ai', text: 'Hi Sofia! 8:00 PM is fully booked, but I can offer 7:30 or 9:00 — both with our window seats. Which works?', time: '8:42 PM' },
      { from: 'them', text: '9:00 is perfect 🍷', time: '8:43 PM' },
      { from: 'ai', text: "Confirmed — Saturday, table for 4 at 9:00 PM. We've saved you a window seat. Buona cena!", time: '8:43 PM', confirm: true },
      { from: 'them', text: 'One question, do you have a kids menu?', time: '8:44 PM' },
    ],
    aiActive: true,
  },
  { id: 2, name: 'Marco Rossi', ch: 'instagram', avatar: 'MR', status: 'AI', unread: 0, time: '8m',
    preview: 'Yes, gluten-free options available...',
    messages: [
      { from: 'them', text: 'Do you have gluten-free pasta?', time: '7:15 PM' },
      { from: 'ai', text: "Yes! We have gluten-free penne and spaghetti made fresh daily. Our risotto and grilled dishes are also naturally GF. Want me to flag your booking?", time: '7:15 PM' },
    ],
    aiActive: true,
  },
  { id: 3, name: 'Ana Pereira', ch: 'email', avatar: 'AP', status: 'human', unread: 2, time: '14m',
    preview: 'I need help with last night\'s receipt',
    messages: [
      { from: 'them', text: 'Hello, I had dinner at Volta last night and I need a receipt for my company expenses. Could you help me?', time: '6:22 PM' },
      { from: 'ai', text: "I can help with that. To find the right receipt, could you share the name on the booking and approximate time?", time: '6:22 PM' },
      { from: 'them', text: 'Booking was under "Pereira", around 8 PM, table for 6.', time: '6:30 PM' },
      { from: 'them', text: '@team can someone send this please?', time: '6:31 PM' },
    ],
    aiActive: false,
  },
  { id: 4, name: 'Chen Liu', ch: 'whatsapp', avatar: 'CL', status: 'AI', unread: 0, time: '22m',
    preview: 'Tomorrow 7:30 for 3 — confirmed',
    messages: [
      { from: 'them', text: '3 of us at 7:30 tomorrow?', time: '5:48 PM' },
      { from: 'ai', text: "Got you — Wednesday 7:30 PM, party of 3. Confirmed. See you tomorrow!", time: '5:48 PM', confirm: true },
    ],
    aiActive: true,
  },
  { id: 5, name: 'Pierre Dubois', ch: 'facebook', avatar: 'PD', status: 'AI', unread: 0, time: '34m',
    preview: 'Oui, ouverts dimanche jusqu\'à 23h',
    messages: [
      { from: 'them', text: "Bonjour, êtes-vous ouverts dimanche?", time: '5:30 PM' },
      { from: 'ai', text: "Bonjour Pierre! Oui, ouverts dimanche de 12h à 23h. Voulez-vous réserver une table?", time: '5:30 PM' },
    ],
    aiActive: true,
  },
  { id: 6, name: 'Emma Stone', ch: 'instagram', avatar: 'ES', status: 'AI', unread: 0, time: '1h',
    preview: 'Moved to Sunday at 8 PM',
    messages: [
      { from: 'them', text: 'Could I move my Saturday booking to Sunday same time?', time: '4:48 PM' },
      { from: 'ai', text: "Done — moved your booking to Sunday 8 PM, party of 2. Have a great weekend!", time: '4:48 PM', confirm: true },
    ],
    aiActive: true,
  },
  { id: 7, name: 'Lukas Schmidt', ch: 'telegram', avatar: 'LS', status: 'pending', unread: 1, time: '2h',
    preview: 'Allergie aux fruits de mer',
    messages: [
      { from: 'them', text: "Hallo, ich habe eine Schalentierallergie. Können Sie ein sicheres Menü vorbereiten?", time: '3:50 PM' },
    ],
    aiActive: false,
  },
];

function ConversationsPage() {
  const [activeId, setActiveId] = useState(1);
  const [filter, setFilter] = useState('All');
  const [draft, setDraft] = useState('');
  const [aiActive, setAiActive] = useState(true);
  const [extraMsgs, setExtraMsgs] = useState({});
  const [aiTyping, setAiTyping] = useState(false);

  const active = CONVOS.find(c => c.id === activeId);
  const allMsgs = [...active.messages, ...(extraMsgs[active.id] || [])];

  // Auto AI reply to Sofia's "kids menu" question after open
  useEffect(() => {
    if (activeId === 1 && !(extraMsgs[1] || []).length && aiActive) {
      const t1 = setTimeout(() => setAiTyping(true), 1400);
      const t2 = setTimeout(() => {
        setAiTyping(false);
        setExtraMsgs(s => ({ ...s, 1: [{ from: 'ai', text: "Yes — we have a special kids menu (€12) with pasta al pomodoro, mini pizzas, and chicken cutlets. We also have high chairs available. See you Saturday!", time: 'now' }] }));
      }, 3500);
      return () => { clearTimeout(t1); clearTimeout(t2); };
    }
  }, [activeId, aiActive]);

  const filtered = CONVOS.filter(c => {
    if (filter === 'All') return true;
    if (filter === 'AI') return c.status === 'AI';
    if (filter === 'Human') return c.status === 'human';
    if (filter === 'Pending') return c.status === 'pending';
    return true;
  });

  const send = (e) => {
    e?.preventDefault();
    if (!draft.trim()) return;
    setExtraMsgs(s => ({ ...s, [active.id]: [...(s[active.id] || []), { from: 'me', text: draft, time: 'now' }] }));
    setDraft('');
  };

  return (
    <AppShell active="conversations">
      <div style={{ display: 'grid', gridTemplateColumns: '360px 1fr', height: '100vh' }}>
        {/* List */}
        <div style={{ borderRight: '1px solid var(--border)', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
          <div style={{ padding: '16px 16px 12px', borderBottom: '1px solid var(--border)' }}>
            <div className="row" style={{ justifyContent: 'space-between', marginBottom: 12 }}>
              <h3 style={{ fontSize: 16, margin: 0 }}>Inbox</h3>
              <span className="badge badge-emerald" style={{ fontSize: 10 }}>{CONVOS.length} active</span>
            </div>
            <div style={{ position: 'relative' }}>
              <Icons.search size={13} style={{ position: 'absolute', left: 11, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-3)' }}/>
              <input className="input" style={{ height: 34, paddingLeft: 32, fontSize: 12.5 }} placeholder="Search conversations..."/>
            </div>
            <div className="row gap-1" style={{ marginTop: 12, padding: 3, background: 'var(--bg-2)', borderRadius: 8 }}>
              {['All', 'AI', 'Human', 'Pending'].map(f => (
                <button key={f} onClick={() => setFilter(f)} style={{
                  flex: 1, padding: '6px 0', fontSize: 11.5,
                  background: filter === f ? 'var(--surface)' : 'transparent',
                  border: 0, borderRadius: 6,
                  color: filter === f ? 'var(--text-0)' : 'var(--text-3)',
                  fontWeight: filter === f ? 500 : 400,
                  cursor: 'default', fontFamily: 'inherit',
                  boxShadow: filter === f ? '0 1px 0 rgba(255,255,255,0.04) inset, 0 1px 2px rgba(0,0,0,0.3)' : 'none',
                }}>{f}</button>
              ))}
            </div>
          </div>
          <div style={{ flex: 1, overflowY: 'auto', minHeight: 0 }}>
            {filtered.map(c => {
              const Ic = Icons[c.ch];
              return (
                <button
                  key={c.id}
                  onClick={() => setActiveId(c.id)}
                  style={{
                    width: '100%', textAlign: 'left',
                    padding: '12px 16px', display: 'flex', gap: 12, alignItems: 'center',
                    background: activeId === c.id ? 'rgba(16,185,129,0.06)' : 'transparent',
                    border: 0, borderBottom: '1px solid var(--border)',
                    borderLeft: '2px solid ' + (activeId === c.id ? 'var(--accent)' : 'transparent'),
                    cursor: 'default', color: 'inherit', fontFamily: 'inherit',
                    transition: 'background .15s',
                  }}
                >
                  <div style={{ position: 'relative' }}>
                    <div className="avatar" style={{ width: 38, height: 38, background: 'linear-gradient(135deg,#52525b,#27272a)', fontSize: 13 }}>{c.avatar}</div>
                    <div className={'avatar ch-' + c.ch} style={{
                      position: 'absolute', bottom: -3, right: -3,
                      width: 18, height: 18, borderRadius: 5,
                      border: '2px solid var(--bg-1)', fontSize: 8,
                    }}><Ic size={9}/></div>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="row" style={{ justifyContent: 'space-between', marginBottom: 2 }}>
                      <span style={{ fontSize: 13, fontWeight: c.unread ? 600 : 500 }}>{c.name}</span>
                      <span className="dim" style={{ fontSize: 10.5 }}>{c.time}</span>
                    </div>
                    <div className="row" style={{ justifyContent: 'space-between', gap: 8 }}>
                      <div className="muted" style={{ fontSize: 11.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', flex: 1 }}>{c.preview}</div>
                      {c.unread > 0 && (
                        <span style={{
                          minWidth: 18, height: 18, padding: '0 5px',
                          borderRadius: 9, background: 'var(--accent)', color: '#052e23',
                          fontSize: 10, fontWeight: 600, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                        }}>{c.unread}</span>
                      )}
                    </div>
                  </div>
                </button>
              );
            })}
          </div>
        </div>

        {/* Thread */}
        <div style={{ display: 'flex', flexDirection: 'column', minWidth: 0, height: '100vh' }}>
          {/* thread header */}
          <div style={{ padding: '14px 24px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 14, background: 'rgba(10,10,12,0.6)', backdropFilter: 'blur(12px)' }}>
            <div className="avatar" style={{ width: 36, height: 36, background: 'linear-gradient(135deg,#52525b,#27272a)', fontSize: 13 }}>{active.avatar}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="row gap-2">
                <span style={{ fontSize: 14, fontWeight: 600 }}>{active.name}</span>
                <span className="dim" style={{ fontSize: 12 }}>·</span>
                <span className={'badge ch-' + active.ch} style={{
                  background: 'rgba(255,255,255,0.04)', color: 'var(--text-2)', border: '1px solid var(--border)',
                  fontSize: 10.5,
                }}>
                  {React.createElement(Icons[active.ch], { size: 11 })} {active.ch}
                </span>
              </div>
              <div className="dim" style={{ fontSize: 11.5, marginTop: 2 }}>Customer since Mar 2025 · 14 visits · €1,840 lifetime</div>
            </div>
            <div className="row gap-2">
              <button
                onClick={() => setAiActive(!aiActive)}
                className={aiActive ? 'badge badge-emerald' : 'badge'}
                style={{ cursor: 'default', padding: '6px 12px', fontSize: 12, border: 'none' }}
              >
                <span style={{ width: 7, height: 7, borderRadius: '50%', background: aiActive ? 'var(--accent)' : 'var(--text-3)', boxShadow: aiActive ? '0 0 6px var(--accent)' : 'none' }}/>
                AI {aiActive ? 'active' : 'paused'}
              </button>
              <button className="btn btn-ghost btn-sm"><Icons.user size={13}/> Take over</button>
              <button className="btn btn-ghost btn-sm"><Icons.more size={14}/></button>
            </div>
          </div>

          {/* messages */}
          <div style={{ flex: 1, overflowY: 'auto', padding: '24px 24px 16px', display: 'flex', flexDirection: 'column', gap: 14, background: 'linear-gradient(180deg, var(--bg-0), var(--bg-1))' }}>
            {allMsgs.map((m, i) => {
              const isMe = m.from === 'me' || m.from === 'ai';
              const isAI = m.from === 'ai';
              return (
                <div key={i} style={{ display: 'flex', justifyContent: isMe ? 'flex-end' : 'flex-start', animation: 'msg-in .3s var(--easing) both' }}>
                  <div style={{ maxWidth: '70%' }}>
                    <div style={{
                      padding: '10px 14px',
                      borderRadius: isMe ? '14px 14px 4px 14px' : '14px 14px 14px 4px',
                      background: isAI
                        ? 'linear-gradient(180deg, rgba(16,185,129,0.18), rgba(16,185,129,0.08))'
                        : isMe
                        ? 'rgba(59,130,246,0.18)'
                        : 'var(--surface)',
                      border: '1px solid ' + (isAI ? 'rgba(16,185,129,0.3)' : isMe ? 'rgba(59,130,246,0.3)' : 'var(--border)'),
                      fontSize: 13.5, lineHeight: 1.5,
                    }}>
                      {(isAI || (isMe && !m.from === 'ai')) && (
                        <div style={{ fontSize: 10.5, color: isAI ? 'var(--accent)' : 'var(--info)', fontWeight: 500, marginBottom: 4, display: 'flex', alignItems: 'center', gap: 4 }}>
                          {isAI ? <><Icons.spark size={10}/> ReplyFlow AI</> : <><Icons.user size={10}/> You</>}
                        </div>
                      )}
                      {m.text}
                      {m.confirm && (
                        <div style={{ marginTop: 8, padding: 8, background: 'rgba(0,0,0,0.25)', borderRadius: 8, display:'flex', alignItems:'center', gap:8, fontSize: 11.5 }}>
                          <Icons.check size={13} stroke="var(--accent)"/>
                          <span>Reservation confirmed</span>
                        </div>
                      )}
                    </div>
                    <div className="dim" style={{ fontSize: 10.5, marginTop: 4, textAlign: isMe ? 'right' : 'left' }}>{m.time}</div>
                  </div>
                </div>
              );
            })}
            {aiTyping && (
              <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                <div style={{
                  padding: '12px 16px',
                  background: 'rgba(16,185,129,0.12)',
                  border: '1px solid rgba(16,185,129,0.25)',
                  borderRadius: '14px 14px 4px 14px',
                  display: 'flex', gap: 5, alignItems: 'center',
                }}>
                  <Icons.spark size={11} stroke="var(--accent)"/>
                  <span style={{ fontSize: 11, color: 'var(--accent)', marginRight: 4 }}>AI is typing</span>
                  {[0,1,2].map(i => (
                    <span key={i} style={{ width: 4, height: 4, borderRadius: '50%', background: 'var(--accent)', animation: `bounce-dot 1.2s ${i*0.15}s ease-in-out infinite` }}/>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* AI banner / input */}
          {aiActive ? (
            <div style={{ padding: '14px 24px', borderTop: '1px solid var(--border)', background: 'linear-gradient(180deg, rgba(16,185,129,0.04), transparent)' }}>
              <div className="card" style={{
                padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 12,
                background: 'rgba(16,185,129,0.06)', borderColor: 'rgba(16,185,129,0.25)',
              }}>
                <div style={{ width: 28, height: 28, borderRadius: 8, background: 'rgba(16,185,129,0.12)', display:'flex', alignItems:'center', justifyContent:'center', color:'var(--accent)' }}>
                  <Icons.spark size={14}/>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 500 }}>AI is handling this conversation</div>
                  <div className="dim" style={{ fontSize: 11 }}>Avg response: 0.6s · You'll be notified if it needs you.</div>
                </div>
                <button onClick={() => setAiActive(false)} className="btn btn-ghost btn-sm">Take over</button>
              </div>
            </div>
          ) : (
            <form onSubmit={send} style={{ padding: '14px 24px', borderTop: '1px solid var(--border)' }}>
              <div className="card" style={{ padding: 8, display: 'flex', gap: 8, alignItems: 'center' }}>
                <button type="button" className="btn btn-ghost btn-sm" style={{ height: 32, padding: '0 8px' }}><Icons.paperclip size={14}/></button>
                <input
                  value={draft}
                  onChange={e => setDraft(e.target.value)}
                  className="input"
                  style={{ height: 36, border: 0, background: 'transparent', flex: 1, fontSize: 13.5 }}
                  placeholder="Type a reply…"
                />
                <button type="button" className="btn btn-ghost btn-sm" style={{ height: 32, padding: '0 10px', color: 'var(--accent)' }}>
                  <Icons.spark size={13}/> Suggest
                </button>
                <button type="submit" className="btn btn-primary btn-sm" disabled={!draft.trim()} style={!draft.trim() ? { opacity: 0.4, pointerEvents: 'none' } : {}}>
                  <Icons.send size={13}/> Send
                </button>
              </div>
            </form>
          )}
        </div>
      </div>
    </AppShell>
  );
}

window.DashboardPage = DashboardPage;
window.ConversationsPage = ConversationsPage;
