// app2.jsx — Reservations, Knowledge Base, Channels

const { useState, useEffect } = React;

// ─────── RESERVATIONS ───────

const RES_DATA = [
  { id: 1, name: 'Galimberti family', email: 'galimberti@email.com', date: '2026-05-06', time: '6:30 PM', size: 4, status: 'confirmed', ch: 'whatsapp', notes: 'Birthday — bring cake' },
  { id: 2, name: 'Riccardo Bianchi',  email: 'r.bianchi@gmail.com', date: '2026-05-06', time: '7:00 PM', size: 2, status: 'confirmed', ch: 'instagram' },
  { id: 3, name: 'Anniversary group', email: 'leo@studio.it',     date: '2026-05-06', time: '7:45 PM', size: 8, status: 'pending',   ch: 'email', notes: 'Wants window-side' },
  { id: 4, name: 'Sofia Marchetti',   email: 'sofia.m@gmail.com', date: '2026-05-06', time: '8:30 PM', size: 4, status: 'confirmed', ch: 'whatsapp', notes: 'Window seat saved' },
  { id: 5, name: 'Walk-in expected',  email: '—',                 date: '2026-05-06', time: '9:15 PM', size: 3, status: 'tentative', ch: 'website' },
  { id: 6, name: 'Chen Liu',          email: 'chen@liu.co',       date: '2026-05-07', time: '7:30 PM', size: 3, status: 'confirmed', ch: 'whatsapp' },
  { id: 7, name: 'Pierre Dubois',     email: 'pierre@dubois.fr',  date: '2026-05-08', time: '8:00 PM', size: 2, status: 'confirmed', ch: 'facebook', notes: 'French speaker' },
  { id: 8, name: 'Emma Stone',        email: 'emma@stone.com',    date: '2026-05-09', time: '8:00 PM', size: 2, status: 'confirmed', ch: 'instagram' },
  { id: 9, name: 'Family of 6',       email: '—',                 date: '2026-05-09', time: '7:00 PM', size: 6, status: 'pending',   ch: 'whatsapp' },
  { id: 10, name: 'Lukas Schmidt',    email: 'lukas@s.de',        date: '2026-05-10', time: '8:30 PM', size: 4, status: 'cancelled', ch: 'telegram', notes: 'Shellfish allergy' },
];

function MonthCalendar({ selectedDay, onSelect }) {
  // Anchor: May 2026
  const month = 'May 2026';
  // First day of May 2026 = Friday (offset 4 if Sunday=0; we use Monday=0 → offset 4)
  const offset = 4;
  const days = 31;
  const dayLabels = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];

  // Reservation count per day
  const counts = {};
  RES_DATA.forEach(r => {
    const d = parseInt(r.date.slice(-2), 10);
    counts[d] = (counts[d] || 0) + 1;
  });

  return (
    <div className="card" style={{ padding: 24 }}>
      <div className="row" style={{ justifyContent: 'space-between', marginBottom: 18 }}>
        <h4>{month}</h4>
        <div className="row gap-2">
          <button className="btn btn-ghost btn-sm" style={{ width: 32, padding: 0 }}>‹</button>
          <button className="btn btn-ghost btn-sm">Today</button>
          <button className="btn btn-ghost btn-sm" style={{ width: 32, padding: 0 }}>›</button>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 4 }}>
        {dayLabels.map(d => (
          <div key={d} className="dim" style={{ fontSize: 11, padding: '6px 4px', textAlign: 'center', fontWeight: 500 }}>{d}</div>
        ))}
        {Array.from({ length: offset }).map((_, i) => <div key={'e'+i}/>)}
        {Array.from({ length: days }).map((_, i) => {
          const day = i + 1;
          const isSelected = day === selectedDay;
          const count = counts[day] || 0;
          const isToday = day === 6;
          return (
            <button
              key={day}
              onClick={() => onSelect(day)}
              style={{
                aspectRatio: '1',
                appearance: 'none', border: 0,
                background: isSelected ? 'rgba(16,185,129,0.15)' : 'transparent',
                color: 'var(--text-1)',
                borderRadius: 8, padding: 6,
                display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                gap: 4, cursor: 'default', fontFamily: 'inherit',
                position: 'relative',
                border: isSelected ? '1px solid rgba(16,185,129,0.4)' : '1px solid transparent',
                transition: 'all .15s',
              }}
            >
              <span style={{ fontSize: 13, fontWeight: isToday ? 600 : 400, color: isToday ? 'var(--accent)' : 'inherit' }}>{day}</span>
              {count > 0 && (
                <div style={{ display: 'flex', gap: 2 }}>
                  {Array.from({ length: Math.min(count, 4) }).map((_, j) => (
                    <span key={j} style={{ width: 4, height: 4, borderRadius: '50%', background: 'var(--accent)', opacity: 0.5 + j*0.15 }}/>
                  ))}
                </div>
              )}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function ResDetailDrawer({ res, onClose }) {
  if (!res) return null;
  const Ic = Icons[res.ch];
  const sBadge = res.status === 'confirmed' ? 'badge-emerald' : res.status === 'pending' ? 'badge-amber' : res.status === 'cancelled' ? 'badge-red' : 'badge-blue';
  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 100,
      background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(4px)',
      animation: 'fade-in .25s ease',
    }} onClick={onClose}>
      <div style={{
        position: 'absolute', right: 0, top: 0, bottom: 0,
        width: 420, background: 'var(--bg-1)',
        borderLeft: '1px solid var(--border)',
        animation: 'slide-in-right .35s var(--easing)',
        display: 'flex', flexDirection: 'column',
      }} onClick={e => e.stopPropagation()}>
        <div className="row" style={{ justifyContent: 'space-between', padding: '20px 24px', borderBottom: '1px solid var(--border)' }}>
          <h4>Reservation details</h4>
          <button onClick={onClose} className="btn btn-ghost btn-sm" style={{ width: 32, padding: 0 }}><Icons.x size={14}/></button>
        </div>
        <div style={{ flex: 1, padding: 24, overflowY: 'auto' }}>
          {/* customer */}
          <div className="card" style={{ padding: 16, marginBottom: 16 }}>
            <div className="row gap-3" style={{ marginBottom: 12 }}>
              <div className="avatar" style={{ width: 44, height: 44, background: 'linear-gradient(135deg,#52525b,#27272a)', fontSize: 15 }}>{res.name[0]}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 15, fontWeight: 600 }}>{res.name}</div>
                <div className="dim" style={{ fontSize: 12 }}>{res.email}</div>
              </div>
              <span className={'badge ' + sBadge} style={{ fontSize: 11 }}>{res.status}</span>
            </div>
            <div className="row gap-2" style={{ fontSize: 12, color: 'var(--text-2)' }}>
              <Ic size={12}/> Booked via {res.ch}
            </div>
          </div>

          {/* details */}
          <div className="card" style={{ padding: 16, marginBottom: 16 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              <div>
                <div className="dim" style={{ fontSize: 11, marginBottom: 4 }}>Date</div>
                <div style={{ fontSize: 13.5 }}>{new Date(res.date).toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric' })}</div>
              </div>
              <div>
                <div className="dim" style={{ fontSize: 11, marginBottom: 4 }}>Time</div>
                <div style={{ fontSize: 13.5 }}>{res.time}</div>
              </div>
              <div>
                <div className="dim" style={{ fontSize: 11, marginBottom: 4 }}>Party size</div>
                <div style={{ fontSize: 13.5 }}>{res.size} guests</div>
              </div>
              <div>
                <div className="dim" style={{ fontSize: 11, marginBottom: 4 }}>Table</div>
                <div style={{ fontSize: 13.5 }}>Auto-assigned</div>
              </div>
            </div>
          </div>

          {res.notes && (
            <div className="card" style={{ padding: 16, marginBottom: 16, background: 'rgba(245,158,11,0.05)', borderColor: 'rgba(245,158,11,0.2)' }}>
              <div style={{ fontSize: 11, color: 'var(--warn)', fontWeight: 600, marginBottom: 4 }}>NOTE FROM AI</div>
              <div style={{ fontSize: 13 }}>{res.notes}</div>
            </div>
          )}

          {/* timeline */}
          <div style={{ marginBottom: 16 }}>
            <div className="dim" style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 12 }}>Timeline</div>
            {[
              { time: '8:43 PM', icon: 'check', text: 'AI confirmed booking' },
              { time: '8:43 PM', icon: 'spark', text: 'AI offered alternative times' },
              { time: '8:42 PM', icon: 'message', text: 'Customer requested table for 4' },
            ].map((t, i) => {
              const Ic2 = Icons[t.icon];
              return (
                <div key={i} className="row gap-3" style={{ padding: '10px 0', borderTop: i > 0 ? '1px solid var(--border)' : 'none' }}>
                  <div style={{ width: 24, height: 24, borderRadius: 6, background: 'rgba(16,185,129,0.1)', color: 'var(--accent)', display:'flex', alignItems:'center', justifyContent:'center' }}>
                    <Ic2 size={12}/>
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 12.5 }}>{t.text}</div>
                    <div className="dim" style={{ fontSize: 11 }}>{t.time}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
        <div style={{ padding: 16, borderTop: '1px solid var(--border)', display: 'flex', gap: 8 }}>
          <button className="btn btn-ghost" style={{ flex: 1 }}><Icons.message size={14}/> Message</button>
          <button className="btn btn-ghost" style={{ flex: 1 }}><Icons.edit size={14}/> Edit</button>
          <button className="btn btn-ghost" style={{ width: 40, padding: 0, color: 'var(--danger)' }}><Icons.trash size={14}/></button>
        </div>
      </div>
    </div>
  );
}

function ReservationsPage() {
  const [view, setView] = useState('calendar');
  const [day, setDay] = useState(6);
  const [selectedRes, setSelectedRes] = useState(null);

  const dayDate = `2026-05-${String(day).padStart(2, '0')}`;
  const filtered = RES_DATA.filter(r => r.date === dayDate);

  return (
    <AppShell active="reservations">
      <AppTopbar title="Reservations" action={<>
        <div className="row gap-1" style={{ padding: 3, background: 'var(--bg-2)', borderRadius: 8 }}>
          {['calendar','list'].map(v => (
            <button key={v} onClick={() => setView(v)} style={{
              padding: '6px 12px', fontSize: 12,
              background: view === v ? 'var(--surface)' : 'transparent',
              border: 0, borderRadius: 6,
              color: view === v ? 'var(--text-0)' : 'var(--text-3)',
              fontWeight: view === v ? 500 : 400,
              cursor: 'default', fontFamily: 'inherit', textTransform: 'capitalize',
            }}>{v}</button>
          ))}
        </div>
        <button className="btn btn-ghost btn-sm"><Icons.filter size={13}/> Filter</button>
      </>}/>

      <div style={{ padding: 32, display: 'flex', flexDirection: 'column', gap: 16 }}>
        {/* stat tiles */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
          <div className="card stat-card">
            <span className="muted" style={{ fontSize: 12 }}>Today's covers</span>
            <div className="stat-num">21</div>
            <span className="stat-delta">↑ 14% vs avg</span>
          </div>
          <div className="card stat-card">
            <span className="muted" style={{ fontSize: 12 }}>This week</span>
            <div className="stat-num">142</div>
            <span className="stat-delta">↑ 8%</span>
          </div>
          <div className="card stat-card">
            <span className="muted" style={{ fontSize: 12 }}>No-show rate</span>
            <div className="stat-num">2.4%</div>
            <span className="stat-delta down">↓ 0.6%</span>
          </div>
          <div className="card stat-card">
            <span className="muted" style={{ fontSize: 12 }}>Avg party size</span>
            <div className="stat-num">3.2</div>
            <span className="muted" style={{ fontSize: 11 }}>guests</span>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: view === 'calendar' ? '1.1fr 1fr' : '1fr', gap: 16 }}>
          {view === 'calendar' && <MonthCalendar selectedDay={day} onSelect={setDay}/>}
          
          {/* day list / table */}
          <div className="card">
            <div className="row" style={{ justifyContent: 'space-between', padding: 20, borderBottom: '1px solid var(--border)' }}>
              <div>
                <h4>{view === 'calendar' ? new Date(dayDate).toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' }) : 'All reservations'}</h4>
                <div className="muted" style={{ fontSize: 12, marginTop: 2 }}>
                  {view === 'calendar' ? `${filtered.length} bookings · ${filtered.reduce((s, r) => s + r.size, 0)} covers` : `${RES_DATA.length} reservations`}
                </div>
              </div>
              <button className="btn btn-primary btn-sm"><Icons.plus size={13}/> Add booking</button>
            </div>
            <div style={{ overflowX: 'auto' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                <thead>
                  <tr style={{ background: 'var(--bg-2)' }}>
                    {(view === 'calendar' ? ['Time','Guest','Party','Channel','Status',''] : ['Date','Time','Guest','Contact','Party','Channel','Status','']).map(h => (
                      <th key={h} style={{ textAlign: 'left', padding: '10px 16px', fontSize: 11, fontWeight: 500, color: 'var(--text-3)', letterSpacing: '0.04em', textTransform: 'uppercase' }}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {(view === 'calendar' ? filtered : RES_DATA).map((r, i) => {
                    const Ic = Icons[r.ch];
                    const sBadge = r.status === 'confirmed' ? 'badge-emerald' : r.status === 'pending' ? 'badge-amber' : r.status === 'cancelled' ? 'badge-red' : 'badge-blue';
                    return (
                      <tr key={r.id}
                          onClick={() => setSelectedRes(r)}
                          style={{
                            background: i % 2 === 1 ? 'rgba(255,255,255,0.015)' : 'transparent',
                            cursor: 'default',
                            transition: 'background .15s',
                          }}>
                        {view === 'list' && <td style={{ padding: '12px 16px' }}>
                          <span className="mono" style={{ fontSize: 12 }}>{new Date(r.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}</span>
                        </td>}
                        <td style={{ padding: '12px 16px' }}>
                          <span className="mono" style={{ fontSize: 13, fontWeight: 500 }}>{r.time}</span>
                        </td>
                        <td style={{ padding: '12px 16px' }}>
                          <div style={{ fontWeight: 500 }}>{r.name}</div>
                          {r.notes && <div className="dim" style={{ fontSize: 11, marginTop: 2 }}>{r.notes}</div>}
                        </td>
                        {view === 'list' && <td style={{ padding: '12px 16px', color: 'var(--text-2)' }}>{r.email}</td>}
                        <td style={{ padding: '12px 16px' }}>
                          <span className="row gap-2"><Icons.users size={11} stroke="var(--text-3)"/> {r.size}</span>
                        </td>
                        <td style={{ padding: '12px 16px' }}>
                          <div className="row gap-2">
                            <span className={'avatar ch-' + r.ch} style={{ width: 22, height: 22, borderRadius: 6, fontSize: 9 }}><Ic size={11}/></span>
                            <span style={{ fontSize: 12, color: 'var(--text-2)', textTransform: 'capitalize' }}>{r.ch}</span>
                          </div>
                        </td>
                        <td style={{ padding: '12px 16px' }}>
                          <span className={'badge ' + sBadge} style={{ fontSize: 10.5, textTransform: 'capitalize' }}>{r.status}</span>
                        </td>
                        <td style={{ padding: '12px 16px', textAlign: 'right' }}>
                          <button className="btn btn-ghost btn-sm" style={{ width: 28, padding: 0, height: 28 }}><Icons.more size={13}/></button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>

      <ResDetailDrawer res={selectedRes} onClose={() => setSelectedRes(null)}/>
    </AppShell>
  );
}

// ─────── KNOWLEDGE BASE ───────

const KB_DATA = {
  Menu: [
    { id: 1, title: 'Spring 2026 dinner menu', preview: 'Antipasti — Burrata di Andria, fennel, blood orange...', type: 'PDF', size: '2.3MB', updated: '2d ago', status: 'live' },
    { id: 2, title: 'Wine list & pairings', preview: 'House recommendations: Etna Rosso with truffle pasta...', type: 'Doc', updated: '5d ago', status: 'live' },
    { id: 3, title: 'Kids menu (NEW)', preview: 'Pasta al pomodoro, mini margherita, chicken cutlet...', type: 'Text', updated: 'Just now', status: 'training' },
    { id: 4, title: 'Allergen reference', preview: 'Gluten-free, dairy-free, and vegan options across menu', type: 'Doc', updated: '1w ago', status: 'live' },
  ],
  Hours: [
    { id: 5, title: 'Operating hours', preview: 'Tue–Thu 6 PM – 11 PM · Fri–Sat 6 PM – 1 AM · Sun 12 PM – 11 PM · Closed Mon', type: 'Text', updated: '1m ago', status: 'live' },
    { id: 6, title: 'Holiday schedule', preview: 'Closed Aug 12–25 for summer holidays. Christmas Eve closed at 4 PM.', type: 'Text', updated: '2w ago', status: 'live' },
  ],
  Policies: [
    { id: 7, title: 'Cancellation policy', preview: 'Free cancellation up to 4 hours before booking. €15/guest fee for groups of 6+.', type: 'Doc', updated: '3d ago', status: 'live' },
    { id: 8, title: 'Dress code', preview: 'Smart casual. No athletic wear. Children welcome until 9 PM.', type: 'Text', updated: '1mo ago', status: 'live' },
  ],
  FAQ: [
    { id: 9, title: 'Do you have parking?', preview: 'Valet €15. Public lot 100m at Via Foscolo.', type: 'Text', updated: '1w ago', status: 'live' },
    { id: 10, title: 'Are dogs allowed?', preview: 'Service dogs always. Other dogs welcome on the terrace only.', type: 'Text', updated: '1w ago', status: 'live' },
    { id: 11, title: 'Private events', preview: 'Yes — full restaurant buyout available for 40+ guests. Contact eventi@volta.com', type: 'Text', updated: '2w ago', status: 'live' },
  ],
  Custom: [
    { id: 12, title: 'House tone of voice', preview: 'Warm, brief, never robotic. Italian phrases sparingly. Use first names.', type: 'Text', updated: '1mo ago', status: 'live' },
  ],
};

function AddKbDrawer({ open, onClose }) {
  if (!open) return null;
  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 100,
      background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(4px)',
      animation: 'fade-in .25s ease',
    }} onClick={onClose}>
      <div style={{
        position: 'absolute', right: 0, top: 0, bottom: 0,
        width: 480, background: 'var(--bg-1)',
        borderLeft: '1px solid var(--border)',
        animation: 'slide-in-right .35s var(--easing)',
        display: 'flex', flexDirection: 'column',
      }} onClick={e => e.stopPropagation()}>
        <div className="row" style={{ justifyContent: 'space-between', padding: '20px 24px', borderBottom: '1px solid var(--border)' }}>
          <div>
            <h4>Add knowledge</h4>
            <div className="muted" style={{ fontSize: 12, marginTop: 2 }}>Teach your AI something new</div>
          </div>
          <button onClick={onClose} className="btn btn-ghost btn-sm" style={{ width: 32, padding: 0 }}><Icons.x size={14}/></button>
        </div>
        <div style={{ flex: 1, padding: 24, overflowY: 'auto' }}>
          <div style={{ marginBottom: 16 }}>
            <label className="label">Category</label>
            <select className="input" style={{ height: 44, fontFamily: 'inherit' }}>
              {Object.keys(KB_DATA).map(c => <option key={c}>{c}</option>)}
            </select>
          </div>
          <div style={{ marginBottom: 16 }}>
            <label className="label">Title</label>
            <input className="input" placeholder="e.g. Sunday brunch menu"/>
          </div>
          <div style={{ marginBottom: 16 }}>
            <label className="label">Content</label>
            <textarea
              className="input"
              style={{ height: 200, paddingTop: 12, fontFamily: 'inherit', resize: 'none' }}
              placeholder="Write or paste your content here. The AI will learn from this and answer customer questions accordingly."
            />
          </div>
          <div style={{ marginBottom: 16 }}>
            <label className="label">Or upload a file</label>
            <div style={{
              border: '1.5px dashed var(--border-strong)',
              borderRadius: 12, padding: 24, textAlign: 'center',
              background: 'rgba(255,255,255,0.02)',
            }}>
              <Icons.upload size={20} stroke="var(--text-2)" style={{ marginBottom: 8 }}/>
              <div style={{ fontSize: 13, color: 'var(--text-1)' }}>Drop files or click to browse</div>
              <div className="dim" style={{ fontSize: 11, marginTop: 4 }}>PDF, DOCX, TXT, MD up to 25MB</div>
            </div>
          </div>
          <div className="card" style={{ padding: 14, background: 'rgba(16,185,129,0.04)', borderColor: 'rgba(16,185,129,0.2)' }}>
            <div className="row gap-2" style={{ fontSize: 12, color: 'var(--accent)', marginBottom: 4, fontWeight: 600 }}>
              <Icons.spark size={12}/> AI training
            </div>
            <div style={{ fontSize: 12, color: 'var(--text-2)' }}>
              New knowledge is embedded and live in ~30 seconds. Your AI will start using it for any new conversation immediately.
            </div>
          </div>
        </div>
        <div style={{ padding: 16, borderTop: '1px solid var(--border)', display: 'flex', gap: 8 }}>
          <button onClick={onClose} className="btn btn-ghost" style={{ flex: 1 }}>Cancel</button>
          <button onClick={onClose} className="btn btn-primary" style={{ flex: 1 }}>
            <Icons.spark size={13}/> Train AI
          </button>
        </div>
      </div>
    </div>
  );
}

function KnowledgePage() {
  const [cat, setCat] = useState('Menu');
  const [adding, setAdding] = useState(false);
  const items = KB_DATA[cat];

  return (
    <AppShell active="knowledge">
      <AppTopbar title="Knowledge base" action={
        <button onClick={() => setAdding(true)} className="btn btn-primary btn-sm"><Icons.plus size={13}/> Add knowledge</button>
      }/>

      <div style={{ display: 'grid', gridTemplateColumns: '240px 1fr', minHeight: 'calc(100vh - 65px)' }}>
        {/* category list */}
        <div style={{ borderRight: '1px solid var(--border)', padding: '20px 12px' }}>
          <div className="dim" style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', padding: '0 10px 12px' }}>Categories</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            {Object.entries(KB_DATA).map(([c, items]) => (
              <button
                key={c}
                onClick={() => setCat(c)}
                className="sidebar-item"
                style={{
                  background: cat === c ? 'rgba(16,185,129,0.08)' : 'transparent',
                  color: cat === c ? 'var(--text-0)' : 'var(--text-2)',
                  textAlign: 'left', border: 0, fontFamily: 'inherit', cursor: 'default',
                }}
              >
                <span style={{ flex: 1 }}>{c}</span>
                <span style={{ fontSize: 11, color: 'var(--text-3)' }}>{items.length}</span>
              </button>
            ))}
          </div>

          {/* AI training status */}
          <div className="card" style={{ marginTop: 32, padding: 14 }}>
            <div className="row gap-2" style={{ marginBottom: 8 }}>
              <div style={{ width: 24, height: 24, borderRadius: 6, background: 'rgba(16,185,129,0.12)', color: 'var(--accent)', display:'flex', alignItems:'center', justifyContent:'center' }}>
                <Icons.brain size={12}/>
              </div>
              <div style={{ fontSize: 12, fontWeight: 500 }}>AI training</div>
            </div>
            <div className="row" style={{ justifyContent: 'space-between', marginBottom: 6, fontSize: 11 }}>
              <span className="dim">Embeddings</span>
              <span className="mono" style={{ color: 'var(--accent)' }}>247 / 247</span>
            </div>
            <div style={{ height: 4, background: 'var(--bg-2)', borderRadius: 2, marginBottom: 10 }}>
              <div style={{ width: '100%', height: '100%', background: 'linear-gradient(90deg, #10B981, #34D399)', borderRadius: 2, boxShadow: '0 0 6px rgba(16,185,129,0.5)' }}/>
            </div>
            <div className="row gap-2" style={{ fontSize: 11, color: 'var(--accent)' }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)', boxShadow: '0 0 4px var(--accent)' }}/>
              All knowledge live
            </div>
          </div>
        </div>

        {/* item list */}
        <div style={{ padding: 32 }}>
          <div className="row" style={{ justifyContent: 'space-between', marginBottom: 24 }}>
            <div>
              <h3 style={{ marginBottom: 4 }}>{cat}</h3>
              <p className="muted" style={{ fontSize: 13, margin: 0 }}>{items.length} items · used in 64% of AI replies this week</p>
            </div>
            <div className="row gap-2">
              <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: 36, paddingLeft: 32, fontSize: 13, width: 240 }} placeholder="Search..."/>
              </div>
            </div>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {items.map((it, i) => (
              <Reveal key={it.id} delay={i*40}>
                <div className="card hoverable" style={{ padding: 18 }}>
                  <div className="row" style={{ justifyContent: 'space-between', marginBottom: 8 }}>
                    <div className="row gap-2">
                      <h4 style={{ fontSize: 14, margin: 0 }}>{it.title}</h4>
                      <span className="badge" style={{ fontSize: 10, padding: '2px 8px' }}>{it.type}</span>
                      {it.status === 'training' && <span className="badge badge-amber" style={{ fontSize: 10 }}>
                        <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--warn)', animation: 'pulse 2s infinite' }}/>
                        Training
                      </span>}
                      {it.status === 'live' && <span className="badge badge-emerald" style={{ fontSize: 10 }}>
                        <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)' }}/>
                        Live
                      </span>}
                    </div>
                    <div className="dim" style={{ fontSize: 11 }}>Updated {it.updated}</div>
                  </div>
                  <p className="muted" style={{ fontSize: 13, margin: 0, lineHeight: 1.55 }}>{it.preview}</p>
                  <div className="row gap-2" style={{ marginTop: 14 }}>
                    <button className="btn btn-ghost btn-sm"><Icons.edit size={12}/> Edit</button>
                    <button className="btn btn-ghost btn-sm"><Icons.copy size={12}/> Duplicate</button>
                    <button className="btn btn-ghost btn-sm" style={{ marginLeft: 'auto', color: 'var(--text-3)' }}><Icons.more size={13}/></button>
                  </div>
                </div>
              </Reveal>
            ))}
          </div>
        </div>
      </div>

      <AddKbDrawer open={adding} onClose={() => setAdding(false)}/>
    </AppShell>
  );
}

// ─────── CHANNELS ───────

const CHANNELS_LIST = [
  { id: 'whatsapp', name: 'WhatsApp Business', desc: 'The world\'s most-used messaging app. Connect via QR.', volume: '4,128', status: 'connected', primary: true, connect: 'qr' },
  { id: 'instagram', name: 'Instagram', desc: 'Reply to DMs and story replies automatically.', volume: '2,610', status: 'connected', connect: 'oauth' },
  { id: 'facebook', name: 'Facebook Messenger', desc: 'Page inbox + Marketplace messages.', volume: '1,184', status: 'connected', connect: 'oauth' },
  { id: 'telegram', name: 'Telegram', desc: 'Add a Bot Token to start chatting.', volume: '648', status: 'disconnected', connect: 'token' },
  { id: 'viber', name: 'Viber', desc: 'Connect via Business inbox.', volume: '0', status: 'disconnected', connect: 'oauth' },
  { id: 'email', name: 'Email', desc: 'Forward your reservations@ inbox.', volume: '1,290', status: 'connected', connect: 'imap' },
  { id: 'website', name: 'Website widget', desc: 'Drop our widget on your site for live chat.', volume: '538', status: 'connected', connect: 'embed' },
  { id: 'sms', name: 'SMS', desc: 'Twilio-powered SMS for confirmations and reminders.', volume: '0', status: 'disconnected', connect: 'token' },
];

function ChannelDetail({ ch, onClose }) {
  if (!ch) return null;
  const Ic = Icons[ch.id];
  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 100,
      background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(4px)',
      animation: 'fade-in .25s ease',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 32,
    }} onClick={onClose}>
      <div className="card" style={{
        width: '100%', maxWidth: 520,
        animation: 'scale-in .3s var(--easing)',
        background: 'var(--bg-1)',
      }} onClick={e => e.stopPropagation()}>
        <div className="row" style={{ justifyContent: 'space-between', padding: '20px 24px', borderBottom: '1px solid var(--border)' }}>
          <div className="row gap-3">
            <div className={'avatar ch-' + ch.id} style={{ width: 40, height: 40, borderRadius: 10 }}><Ic size={18}/></div>
            <div>
              <h4>Connect {ch.name}</h4>
              <div className="muted" style={{ fontSize: 12, marginTop: 2 }}>{ch.desc}</div>
            </div>
          </div>
          <button onClick={onClose} className="btn btn-ghost btn-sm" style={{ width: 32, padding: 0 }}><Icons.x size={14}/></button>
        </div>
        <div style={{ padding: 28 }}>
          {ch.connect === 'qr' && (
            <div style={{ textAlign: 'center' }}>
              <div className="muted" style={{ fontSize: 13, marginBottom: 20 }}>Scan with your phone's WhatsApp app</div>
              <div style={{
                width: 220, height: 220, margin: '0 auto',
                background: 'white', borderRadius: 12, padding: 16,
                position: 'relative',
                boxShadow: '0 0 0 1px var(--border)',
              }}>
                {/* fake QR */}
                <svg viewBox="0 0 21 21" style={{ width: '100%', height: '100%' }} shapeRendering="crispEdges">
                  {Array.from({ length: 21 }).map((_, y) =>
                    Array.from({ length: 21 }).map((_, x) => {
                      const isCorner = (x < 7 && y < 7) || (x > 13 && y < 7) || (x < 7 && y > 13);
                      const isInside = isCorner && (x > 0 && x < 6 && y > 0 && y < 6) || (x > 14 && x < 20 && y > 0 && y < 6) || (x > 0 && x < 6 && y > 14 && y < 20);
                      const isCornerCenter = (x > 1 && x < 5 && y > 1 && y < 5) || (x > 15 && x < 19 && y > 1 && y < 5) || (x > 1 && x < 5 && y > 15 && y < 19);
                      const r = (x * 7 + y * 13 + 3) % 5;
                      const fill = isCornerCenter || (isCorner && (x === 0 || x === 6 || y === 0 || y === 6 || x === 14 || x === 20 || y === 14)) || (!isCorner && r < 2);
                      return fill ? <rect key={x+'-'+y} x={x} y={y} width="1" height="1" fill="#0a0a0a"/> : null;
                    })
                  )}
                </svg>
                <div style={{
                  position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)',
                  width: 36, height: 36, borderRadius: 8, background: 'var(--accent)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  border: '3px solid white',
                }}><Icons.whatsapp size={18} stroke="white"/></div>
              </div>
              <div className="dim" style={{ fontSize: 12, marginTop: 16 }}>QR refreshes in 0:42</div>
            </div>
          )}
          {ch.connect === 'oauth' && (
            <div style={{ textAlign: 'center', padding: '20px 0' }}>
              <p style={{ fontSize: 14, color: 'var(--text-1)', marginBottom: 24, lineHeight: 1.5 }}>
                You'll be redirected to {ch.name} to authorize ReplyFlow. We only request the permissions needed to read and reply to messages.
              </p>
              <button onClick={onClose} className="btn btn-primary btn-lg" style={{ width: '100%' }}>
                Continue with {ch.name} <Icons.external size={14}/>
              </button>
            </div>
          )}
          {ch.connect === 'token' && (
            <div>
              <label className="label">Bot token</label>
              <input className="input mono" placeholder="123456789:AAEhBOweik6aB...." style={{ fontSize: 12.5 }}/>
              <p className="dim" style={{ fontSize: 11.5, marginTop: 8, lineHeight: 1.5 }}>
                Get your token from @BotFather on Telegram. <a href="#" onClick={e=>e.preventDefault()} style={{ color: 'var(--accent)' }}>How to get a token →</a>
              </p>
              <button onClick={onClose} className="btn btn-primary" style={{ width: '100%', marginTop: 20 }}>Connect bot</button>
            </div>
          )}
          {ch.connect === 'imap' && (
            <div>
              <div style={{ marginBottom: 12 }}>
                <label className="label">IMAP server</label>
                <input className="input" placeholder="imap.gmail.com"/>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 12 }}>
                <div>
                  <label className="label">Port</label>
                  <input className="input mono" placeholder="993"/>
                </div>
                <div>
                  <label className="label">Encryption</label>
                  <select className="input" style={{ fontFamily: 'inherit' }}><option>SSL/TLS</option><option>STARTTLS</option><option>None</option></select>
                </div>
              </div>
              <div style={{ marginBottom: 12 }}>
                <label className="label">Email</label>
                <input className="input" placeholder="reservations@volta.com"/>
              </div>
              <div style={{ marginBottom: 12 }}>
                <label className="label">App password</label>
                <input className="input" type="password" placeholder="••••••••"/>
              </div>
              <button onClick={onClose} className="btn btn-primary" style={{ width: '100%', marginTop: 8 }}>Connect inbox</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function ChannelsPage() {
  const [active, setActive] = useState(null);
  const stats = {
    total: CHANNELS_LIST.reduce((s, c) => s + parseInt(c.volume.replace(',',''), 10), 0),
    connected: CHANNELS_LIST.filter(c => c.status === 'connected').length,
  };

  return (
    <AppShell active="channels">
      <AppTopbar title="Channels"/>

      <div style={{ padding: 32, display: 'flex', flexDirection: 'column', gap: 24 }}>
        {/* hero */}
        <div className="card" style={{ padding: 28, position: 'relative', overflow: 'hidden' }}>
          <div style={{
            position: 'absolute', top: -100, right: -100, 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' }}>
            <h3 style={{ marginBottom: 8 }}>Connect every channel your customers use</h3>
            <p className="muted" style={{ fontSize: 14, margin: 0, marginBottom: 20, maxWidth: 560, lineHeight: 1.55 }}>
              Once connected, ReplyFlow handles every message in one unified inbox. Add or remove channels anytime.
            </p>
            <div className="row gap-6">
              <div>
                <div className="dim" style={{ fontSize: 11, marginBottom: 4 }}>Channels connected</div>
                <div style={{ fontSize: 22, fontWeight: 600 }}>{stats.connected} <span className="muted" style={{ fontSize: 14 }}>/ {CHANNELS_LIST.length}</span></div>
              </div>
              <div>
                <div className="dim" style={{ fontSize: 11, marginBottom: 4 }}>Messages this month</div>
                <div style={{ fontSize: 22, fontWeight: 600 }}>{stats.total.toLocaleString()}</div>
              </div>
              <div>
                <div className="dim" style={{ fontSize: 11, marginBottom: 4 }}>Avg AI response</div>
                <div style={{ fontSize: 22, fontWeight: 600, color: 'var(--accent)' }}>0.6s</div>
              </div>
            </div>
          </div>
        </div>

        {/* grid */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
          {CHANNELS_LIST.map((c, i) => {
            const Ic = Icons[c.id];
            const isOn = c.status === 'connected';
            return (
              <Reveal key={c.id} delay={i*40}>
                <div className="card hoverable" style={{ padding: 22, position: 'relative' }}>
                  {c.primary && <span className="badge badge-emerald" style={{ position: 'absolute', top: 16, right: 16, fontSize: 10 }}>Primary</span>}
                  <div className={'avatar ch-' + c.id} style={{ width: 44, height: 44, borderRadius: 12, marginBottom: 14 }}>
                    <Ic size={20}/>
                  </div>
                  <div className="row gap-2" style={{ marginBottom: 6 }}>
                    <h4>{c.name}</h4>
                    {isOn && <span className="row gap-1" style={{ fontSize: 10.5, color: 'var(--accent)' }}>
                      <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)', boxShadow: '0 0 4px var(--accent)' }}/>
                      Live
                    </span>}
                  </div>
                  <p className="muted" style={{ fontSize: 13, margin: 0, marginBottom: 16, lineHeight: 1.5, minHeight: 38 }}>{c.desc}</p>
                  <div className="row" style={{ justifyContent: 'space-between', alignItems: 'center', borderTop: '1px solid var(--border)', paddingTop: 14 }}>
                    <div className="dim" style={{ fontSize: 11 }}>
                      {isOn ? <><span style={{ color: 'var(--text-1)', fontWeight: 500 }}>{c.volume}</span> messages this month</> : 'Not connected'}
                    </div>
                    {isOn ? (
                      <button className="btn btn-ghost btn-sm">Manage</button>
                    ) : (
                      <button onClick={() => setActive(c)} className="btn btn-primary btn-sm">Connect</button>
                    )}
                  </div>
                </div>
              </Reveal>
            );
          })}
        </div>
      </div>

      <ChannelDetail ch={active} onClose={() => setActive(null)}/>
    </AppShell>
  );
}

window.ReservationsPage = ReservationsPage;
window.KnowledgePage = KnowledgePage;
window.ChannelsPage = ChannelsPage;
