/* global React */
// ============================================================
// Pelcro Admin — faithful recreation of the real product UI
// Navy sidebar #0B1626 · teal #14B8A6 · light canvas #F5F7F9
// ============================================================

const TEAL = '#14B8A6';
const NAVY = '#0B1626';
const INK = '#16202E';

// — Pelcro shield logo —
function PelcroLogo() {
  return <img src="assets/pelcro-logo-white.png" alt="Pelcro" style={{ height: 30, width: 'auto', display: 'block' }} />;
}

const ICONS = {
  overview: '◷', ai: '🤖', customers: '👥', billing: '▭', products: '🛍', ecom: '🔒',
  payable: '🧾', accounting: '🧮', newsletter: '✉', collections: '▦', settings: '⚙',
};

const NAV = [
  { id: 'overview', label: 'Overview' },
  { id: 'ai', label: 'AI', aiBadge: true, caret: true },
  { id: 'customers', label: 'Customers', caret: true, children: [
    { id: 'customers-list', label: 'Customers' }, { id: 'addresses', label: 'Addresses' },
    { id: 'organizations', label: 'Organizations' }, { id: 'tickets', label: 'Tickets' },
  ]},
  { id: 'billing', label: 'Billing', caret: true },
  { id: 'products', label: 'Products', caret: true, children: [
    { id: 'products-list', label: 'Products' }, { id: 'coupons', label: 'Coupons' },
  ]},
  { id: 'ecom', label: 'E-Commerce', caret: true },
  { id: 'payable', label: 'Payable', caret: true, children: [
    { id: 'vendors', label: 'Vendors' }, { id: 'bills', label: 'Bills' },
  ]},
  { id: 'accounting', label: 'Accounting', caret: true },
  { id: 'newsletter', label: 'Newsletter', caret: true },
  { id: 'collections', label: 'Collections', caret: true },
];

function NavIcon({ id, active }) {
  const c = active ? TEAL : '#8A97A8';
  const p = { width: 20, height: 20, stroke: c, strokeWidth: 1.7, fill: 'none', strokeLinecap: 'round', strokeLinejoin: 'round' };
  switch (id) {
    case 'overview': return <svg viewBox="0 0 24 24" {...p}><circle cx="12" cy="12" r="9"/><path d="M12 12l4-2.5"/><circle cx="12" cy="12" r="1.4" fill={c} stroke="none"/></svg>;
    case 'ai': return <svg viewBox="0 0 24 24" {...p}><rect x="5" y="8" width="14" height="11" rx="2.5"/><path d="M12 8V5M9 4.5h6"/><circle cx="9.5" cy="13" r="1" fill={c} stroke="none"/><circle cx="14.5" cy="13" r="1" fill={c} stroke="none"/></svg>;
    case 'customers': return <svg viewBox="0 0 24 24" {...p}><circle cx="9" cy="8" r="3"/><path d="M3.5 19a5.5 5.5 0 0 1 11 0M16 6.5a3 3 0 0 1 0 5.5M20.5 19a5 5 0 0 0-3.5-4.7"/></svg>;
    case 'billing': return <svg viewBox="0 0 24 24" {...p}><rect x="3" y="6" width="18" height="12" rx="2"/><path d="M3 10h18"/></svg>;
    case 'products': return <svg viewBox="0 0 24 24" {...p}><path d="M5 8h14l-1 11H6L5 8Z"/><path d="M9 8V6a3 3 0 0 1 6 0v2"/></svg>;
    case 'ecom': return <svg viewBox="0 0 24 24" {...p}><rect x="5" y="10" width="14" height="10" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0v3"/></svg>;
    case 'payable': return <svg viewBox="0 0 24 24" {...p}><path d="M6 3h9l3 3v15l-2-1.2L14 21l-2-1.2L10 21l-2-1.2L6 21V3Z"/><path d="M9 8h6M9 12h6"/></svg>;
    case 'accounting': return <svg viewBox="0 0 24 24" {...p}><rect x="5" y="3" width="14" height="18" rx="2"/><path d="M8 7h8M8 11h3M13 11h3M8 15h3M13 15h3"/></svg>;
    case 'newsletter': return <svg viewBox="0 0 24 24" {...p}><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3.5 6.5 12 13l8.5-6.5"/></svg>;
    case 'collections': return <svg viewBox="0 0 24 24" {...p}><path d="M12 3 3 8l9 5 9-5-9-5ZM3 13l9 5 9-5M3 17.5l9 5 9-5" /></svg>;
    case 'settings': return <svg viewBox="0 0 24 24" {...p}><circle cx="12" cy="12" r="3"/><path d="M12 3v2.5M12 18.5V21M4.2 7l2.2 1.3M17.6 15.7l2.2 1.3M4.2 17l2.2-1.3M17.6 8.3l2.2-1.3"/></svg>;
    default: return null;
  }
}

function Sidebar({ view, onNav, tourRefs }) {
  const groups = {
    customers: ['customers-list','customer-detail','addresses','organizations','tickets'],
    products: ['products-list','create-product','coupons'],
    payable: ['vendors','bills'],
    ai: ['ai-agent'],
  };
  const activeTop = (id) => view === id || (groups[id] && groups[id].includes(view));
  return (
    <aside style={S.sidebar}>
      <div style={{ padding: '20px 22px 22px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <span style={{ color: '#8A97A8', fontSize: 20, cursor: 'pointer' }}>≡</span>
          <PelcroLogo />
        </div>
      </div>
      <nav style={{ flex: 1, overflowY: 'auto', padding: '0 14px' }}>
        {NAV.map(n => {
          const act = activeTop(n.id);
          const expanded = n.children && act;
          const childActive = (c) => view === c.id || (c.id === 'customers-list' && view === 'customer-detail') || (c.id === 'products-list' && view === 'create-product');
          return (
            <div key={n.id}>
              <div ref={el => { if (tourRefs) tourRefs.current['nav-' + n.id] = el; }}
                onClick={() => onNav(n.id)} style={{ ...S.navItem, ...(act ? S.navItemActive : null) }}>
                <span style={{ width: 22, display: 'flex', justifyContent: 'center' }}><NavIcon id={n.id} active={act} /></span>
                <span style={{ flex: 1 }}>{n.label}</span>
                {n.aiBadge && <span style={S.aiBadge}>AI</span>}
                {n.caret && <span style={{ color: '#5E6B7E', fontSize: 11 }}>⌄</span>}
              </div>
              {expanded && (
                <div style={{ paddingLeft: 8 }}>
                  {n.children.map(c => {
                    const cact = childActive(c);
                    return (
                      <div key={c.id} ref={el => { if (tourRefs) tourRefs.current['nav-' + c.id] = el; }}
                        onClick={(e) => { e.stopPropagation(); onNav(c.id); }} style={{ ...S.subItem, ...(cact ? S.subItemActive : null) }}>
                        {c.label}
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          );
        })}
      </nav>
      <div style={{ padding: '12px 14px 18px' }}>
        <div style={S.settingsBtn}><span style={{ width: 22, display: 'flex', justifyContent: 'center' }}><NavIcon id="settings" /></span> Settings</div>
      </div>
    </aside>
  );
}

function TopBar({ tourRefs }) {
  return (
    <div style={S.topbar}>
      <div style={{ flex: 1 }} />
      <div style={S.siteSwitch}><span style={{ width: 8, height: 8, borderRadius: 4, background: '#22C55E' }} /> thetribune.com <span style={{ color: '#5E6B7E' }}>⌄</span></div>
      <div style={S.helpBtn}>?</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginLeft: 6 }}>
        <div style={S.userAvatar}>n</div>
        <div style={{ lineHeight: 1.2 }}>
          <div style={{ color: '#fff', fontWeight: 600, fontSize: 14 }}>nataliia</div>
          <div style={{ color: '#8A97A8', fontSize: 12 }}>Administrator</div>
        </div>
        <span style={{ color: '#5E6B7E' }}>⌄</span>
      </div>
    </div>
  );
}

function PageTitle({ children, crumbs }) {
  return (
    <>
      <h1 style={{ fontSize: 38, fontWeight: 800, color: INK, margin: '0 0 8px', letterSpacing: '-0.02em' }}>{children}</h1>
      <div style={{ width: 116, height: 4, borderRadius: 4, background: TEAL, marginBottom: crumbs ? 22 : 26 }} />
      {crumbs && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, color: '#5E6B7E', fontSize: 14, marginBottom: 26 }}>
          {crumbs.map((c, i) => (
            <React.Fragment key={i}>
              {i > 0 && <span style={{ color: '#C2CBD6' }}>›</span>}
              <span style={{ fontWeight: i === crumbs.length - 1 ? 700 : 500, color: i === crumbs.length - 1 ? INK : '#5E6B7E' }}>{i === 0 ? '⌂ ' : ''}{c}</span>
            </React.Fragment>
          ))}
        </div>
      )}
    </>
  );
}

// — sparkline bars —
function Spark({ data, color = TEAL, accent }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 1.5, height: 42 }}>
      {data.map((v, i) => (
        <div key={i} style={{ flex: 1, height: `${Math.max(4, v)}%`, background: (accent && accent.includes(i)) ? '#E0455E' : color, borderRadius: 1, opacity: 0.92 }} />
      ))}
    </div>
  );
}
const bars1 = [60,72,68,80,74,90,85,78,82,70,66,72,68,64,60,58,55,60,57,54,52,50,55,58,54,50,48,52,56,50,48];
const bars2 = [0,0,8,0,0,22,0,0,12,0,8,0,0,0,28,0,0,0,0,0,10,0,0,0,0,0,0,0,12,0,6];
const bars3 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,30,0,0,0,0,0];

// ============================================================
// OVERVIEW
// ============================================================
function OverviewView({ tourRefs }) {
  return (
    <div style={S.page}>
      <PageTitle>Overview — The Tribune</PageTitle>
      <div style={S.dateRange}>
        <span style={{ color: '#5E6B7E' }}>▦</span> <span style={{ color: '#5E6B7E' }}>Date range</span> <b style={{ color: TEAL }}>Last month</b> <span style={{ color: '#5E6B7E' }}>⌄</span>
      </div>

      <div style={S.kpiRow} ref={el => { if (tourRefs) tourRefs.current['kpi-row'] = el; }}>
        <Kpi label="Monthly Recurring Revenue" value="$1,489,850.42" unit="CAD" />
        <Kpi label="Subscription Gross Revenue" value="$788,229" unit="CAD" spark={bars1} axis />
        <Kpi label="New Subscribers" value="40" spark={bars2} axis />
        <Kpi label="New Customers" value="1,085" spark={bars3} axis />
        <Kpi label="Churned Customers" value="0" note="No activity in the selected period" last />
      </div>

      <div style={S.panel} ref={el => { if (tourRefs) tourRefs.current['activity'] = el; }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 22 }}>
          <div style={{ fontSize: 22, fontWeight: 800, color: INK, whiteSpace: 'nowrap' }}>Customer Activity</div>
          <span style={{ color: TEAL, fontWeight: 600, fontSize: 14 }}>View all →</span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 40 }}>
          <div>
            <div style={{ color: '#5E6B7E', fontSize: 14, marginBottom: 18 }}>Top event types</div>
            {[['Modal Displayed', 4135, 1],['Page Viewed', 1524, 0.42],['Logged In', 66, 0.12],['Customer Address Created', 20, 0.08]].map(([l,v,w]) => (
              <div key={l} style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 20 }}>
                <div style={{ flex: '0 0 200px', color: INK, fontSize: 15 }}>{l}</div>
                <div style={{ flex: 1, height: 8, background: '#EEF1F4', borderRadius: 4 }}><div style={{ width: `${w*100}%`, height: '100%', background: TEAL, borderRadius: 4 }} /></div>
                <div style={{ flex: '0 0 54px', textAlign: 'right', fontWeight: 700, color: INK }}>{v.toLocaleString()}</div>
              </div>
            ))}
          </div>
          <div>
            <div style={{ color: '#5E6B7E', fontSize: 14, marginBottom: 18 }}>Events by country</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 26 }}>
              <div style={{ width: 150, height: 150, borderRadius: '50%', background: 'conic-gradient(#3B82F6 0 58%, #10B981 58% 69%, #F59E0B 69% 78%, #EC4899 78% 79%, #3B82F6 79% 100%)' }} />
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12, fontSize: 14 }}>
                {[['#3B82F6','Egypt'],['#10B981','Italy'],['#F59E0B','Canada'],['#EC4899','United States']].map(([c,l]) => (
                  <div key={l} style={{ display: 'flex', alignItems: 'center', gap: 9, color: INK }}><span style={{ width: 11, height: 11, borderRadius: 6, background: c }} />{l}</div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Kpi({ label, value, unit, spark, axis, note, last }) {
  return (
    <div style={{ ...S.kpi, borderRight: last ? 'none' : '1px solid #EEF1F4' }}>
      <div style={{ color: '#5E6B7E', fontSize: 15, marginBottom: 14, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{label}</div>
      <div style={{ fontSize: 24, fontWeight: 800, color: INK, letterSpacing: '-0.02em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{value} {unit && spark && <span style={{ fontSize: 14, fontWeight: 600, color: '#8A97A8' }}>{unit}</span>}</div>
      {unit && !spark && <div style={{ fontSize: 13, color: '#8A97A8', marginTop: 8, borderBottom: '1px dashed #C2CBD6', display: 'inline-block' }}>{unit}</div>}
      {spark && <div style={{ marginTop: 16 }}><Spark data={spark} accent={spark === bars2 ? [] : []} />
        <div style={{ display: 'flex', justifyContent: 'space-between', color: '#A6B0BD', fontSize: 12, marginTop: 6 }}><span>01 May</span><span>31 May</span></div></div>}
      {note && <div style={{ fontSize: 14, color: '#A6B0BD', fontStyle: 'italic', marginTop: 22 }}>{note}</div>}
    </div>
  );
}

// ============================================================
// CUSTOMERS LIST
// ============================================================
const CUSTOMERS = [
  { n: 'James Whitfield', e: 'j.whitfield@gmail.com', p: '4163920184' },
  { n: 'Eleanor Hayes', e: 'eleanor.hayes@outlook.com', p: '6478815503' },
  { n: 'Sofia Mendez', e: 'sofia.mendez@gmail.com', p: '5142008891' },
  { n: 'Marcus Lindgren', e: 'm.lindgren@outlook.com', p: '4380097712' },
  { n: 'Priya Raghunathan', e: 'priya.raghunathan@gmail.com', p: '6139923014' },
];
function CustomersView({ tourRefs, onOpen }) {
  return (
    <div style={S.page}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <PageTitle crumbs={['Home', 'Customers']}>Customers</PageTitle>
        <span style={{ color: TEAL, fontWeight: 600, fontSize: 14, display: 'flex', alignItems: 'center', gap: 6 }}>▭ Docs</span>
      </div>
      <div style={S.searchRow}>
        <div style={S.selectBox}>All <span style={{ color: '#8A97A8' }}>⌄</span></div>
        <span style={{ color: '#8A97A8', fontWeight: 600 }}>IN</span>
        <div style={S.searchInput}>🔍 <span style={{ color: '#A6B0BD' }}>Search All</span></div>
        <button style={S.searchBtn}>🔍</button>
        <button style={S.filterBtn}>⚙ Filter</button>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', marginBottom: 14 }}>
        <div style={{ color: '#5E6B7E', fontSize: 15 }}>25 results</div>
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 12 }}>
          <button style={S.ghostBtn}>▦ Columns ⌄</button>
          <button style={S.ghostBtn}>⤓ Export</button>
          <button style={S.ghostBtn}>⊞ Metadata</button>
          <button style={S.primaryBtn} ref={el => { if (tourRefs) tourRefs.current['new-customer'] = el; }}>+ New Customer</button>
        </div>
      </div>
      <div style={S.tableCard} ref={el => { if (tourRefs) tourRefs.current['cust-table'] = el; }}>
        <div style={{ ...S.tr, color: '#8A97A8', fontSize: 12, letterSpacing: '.05em', fontWeight: 700, borderBottom: '1px solid #EEF1F4' }}>
          <div style={{ flex: 2 }}>NAME ⇅</div><div style={{ flex: 3 }}>EMAIL ⇅</div><div style={{ flex: 1.4 }}>PHONE</div><div style={{ flex: 0.6, textAlign: 'right' }}>ACTIONS</div>
        </div>
        {CUSTOMERS.map((c, i) => (
          <div key={i} onClick={() => i === 0 && onOpen && onOpen()} style={{ ...S.tr, borderBottom: i < CUSTOMERS.length-1 ? '1px solid #F1F4F7' : 'none', cursor: i===0?'pointer':'default' }}
            ref={el => { if (i === 0 && tourRefs) tourRefs.current['cust-row-0'] = el; }}>
            <div style={{ flex: 2, display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={S.custAvatar}>{c.n[0]}</div><span style={{ fontWeight: 600, color: INK }}>{c.n}</span>
            </div>
            <div style={{ flex: 3, color: '#5E6B7E' }}>{c.e}</div>
            <div style={{ flex: 1.4, color: '#5E6B7E' }}>{c.p}</div>
            <div style={{ flex: 0.6, textAlign: 'right', color: '#A6B0BD' }}>•••</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============================================================
// CUSTOMER DETAIL (Boris Lind)
// ============================================================
function CustomerDetailView({ tourRefs }) {
  const tabs = ['Subscriptions','Invoices','Payments','Orders','Payment Methods','Addresses','Memberships','Activity','Tickets'];
  return (
    <div style={S.page}>
      <PageTitle crumbs={['Home', 'Customers', 'James Whitfield']}>James Whitfield</PageTitle>
      <div style={S.detailCard}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 18 }}>
          <div style={{ position: 'relative' }}>
            <div style={{ ...S.custAvatar, width: 64, height: 64, fontSize: 24 }}>JW</div>
            <div style={{ position: 'absolute', top: -2, right: -2, width: 22, height: 22, borderRadius: 11, background: '#F59E0B', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 12 }}>★</div>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ fontSize: 26, fontWeight: 800, color: INK }}>James Whitfield</div>
              <span style={{ background: '#EAFBF7', color: TEAL, fontSize: 12, fontWeight: 700, padding: '4px 12px', borderRadius: 999 }}>Print + Digital</span>
            </div>
            <div style={{ display: 'flex', gap: 22, color: '#5E6B7E', fontSize: 14, marginTop: 8, flexWrap: 'wrap' }}>
              <span>✉ j.whitfield@gmail.com</span><span>📞 4163920184</span><span>🏢 Meridian Consulting</span>
            </div>
            <div style={{ color: '#5E6B7E', fontSize: 14, marginTop: 6 }}>Currency: CAD</div>
            <div style={{ color: '#5E6B7E', fontSize: 14, marginTop: 6 }}>📅 Member since Mar 14, 2024 , 09:41 AM (America/Toronto) <span style={{ color: '#A6B0BD' }}>(2 years)</span></div>
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            <button style={S.primaryBtn}>ⓘ Details</button>
            <button style={S.ghostBtn}>✎ Edit</button>
            <button style={{ ...S.ghostBtn, padding: '10px 12px' }}>⋮</button>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 18, marginTop: 26 }}>
          <Stat label="Account Balance" value="$0.00" icon="$" />
          <Stat label="Lifetime Value" value="$897.00" green icon="💵" innerRef={el => { if (tourRefs) tourRefs.current['ltv'] = el; }} />
          <Stat label="Failed Payments" value="0/4" icon="💳" />
          <Stat label="Last Active" value="-" icon="◷" />
        </div>
      </div>
      <div style={{ display: 'flex', gap: 28, marginTop: 24, borderBottom: '1px solid #E6EBF0', overflowX: 'auto' }}>
        {tabs.map((t, i) => (
          <div key={t} style={{ padding: '0 2px 14px', fontWeight: i === 0 ? 700 : 500, color: i === 0 ? TEAL : '#5E6B7E', borderBottom: i === 0 ? `3px solid ${TEAL}` : '3px solid transparent', whiteSpace: 'nowrap', fontSize: 15 }}>{t}</div>
        ))}
      </div>
      <div style={{ ...S.panel, marginTop: 22 }} ref={el => { if (tourRefs) tourRefs.current['subs-card'] = el; }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <span style={{ fontSize: 20, fontWeight: 800, color: INK }}>Subscriptions</span>
          <span style={{ background: '#EEF1F4', color: '#5E6B7E', fontSize: 12, fontWeight: 700, padding: '3px 10px', borderRadius: 999 }}>1 total</span>
          <span style={{ background: '#DCFCE7', color: '#16A34A', fontSize: 12, fontWeight: 700, padding: '3px 10px', borderRadius: 999 }}>1 active</span>
          <button style={{ ...S.primaryBtn, marginLeft: 'auto' }}>+ Add Subscription</button>
        </div>
        <div style={{ color: '#8A97A8', fontSize: 14, marginTop: 8 }}>All subscription plans for this customer</div>
        <div style={{ marginTop: 16, border: '1px solid #EEF1F4', borderRadius: 12, padding: 18, display: 'flex', alignItems: 'center', gap: 16 }}>
          <div style={{ width: 44, height: 44, borderRadius: 10, background: '#EAFBF7', display: 'flex', alignItems: 'center', justifyContent: 'center', color: TEAL, fontSize: 18 }}>↻</div>
          <div style={{ flex: 1 }}><div style={{ fontWeight: 700, color: INK }}>Print + Digital — Annual</div><div style={{ color: '#8A97A8', fontSize: 13 }}>Renews Mar 14, 2027 · $299.00 CAD</div></div>
          <span style={{ background: '#DCFCE7', color: '#16A34A', fontSize: 12, fontWeight: 700, padding: '4px 12px', borderRadius: 999 }}>Active</span>
        </div>
      </div>
    </div>
  );
}
function Stat({ label, value, green, icon, innerRef }) {
  return (
    <div style={S.statCard} ref={innerRef}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div><div style={{ color: '#5E6B7E', fontSize: 14 }}>{label}</div>
          <div style={{ fontSize: 24, fontWeight: 800, color: green ? '#16A34A' : INK, marginTop: 8 }}>{value}</div></div>
        <div style={{ width: 38, height: 38, borderRadius: 19, background: '#F4F6F8', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#8A97A8' }}>{icon}</div>
      </div>
    </div>
  );
}

// ============================================================
// AI AGENT (welcome panel)
// ============================================================
function UserMsg({ children }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 22 }}>
      <div style={{ maxWidth: '76%', background: TEAL, color: '#fff', fontSize: 15, lineHeight: 1.5, padding: '13px 18px', borderRadius: '16px 16px 4px 16px' }}>{children}</div>
    </div>
  );
}
function AIMsg({ children }) {
  return (
    <div style={{ display: 'flex', gap: 14, marginBottom: 28 }}>
      <div style={{ flex: '0 0 36px', width: 36, height: 36, borderRadius: 10, background: '#EAFBF7', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18, color: TEAL }}>🧠</div>
      <div style={{ maxWidth: '78%', background: '#fff', border: '1px solid #E6EBF0', borderRadius: '4px 16px 16px 16px', padding: '16px 20px', color: INK, fontSize: 15, lineHeight: 1.6 }}>{children}</div>
    </div>
  );
}
function AIAgentView({ tourRefs }) {
  return (
    <div style={{ ...S.page, maxWidth: 820, margin: '0 auto', paddingTop: 30 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 28 }}>
        <div style={{ width: 44, height: 44, borderRadius: 12, background: '#EAFBF7', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22, color: TEAL }}>🧠</div>
        <div>
          <div style={{ fontSize: 22, fontWeight: 800, color: INK }}>Pelcro AI Agent</div>
          <div style={{ color: '#8A97A8', fontSize: 13, display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ width: 7, height: 7, borderRadius: 4, background: '#22C55E' }} /> Connected to thetribune.com data</div>
        </div>
      </div>

      <div ref={el => { if (tourRefs) tourRefs.current['ai-suggested'] = el; }}>
        <UserMsg>How many subscribers did we lose last month, and what plan were they on?</UserMsg>
        <AIMsg>
          <div style={{ marginBottom: 12 }}>You had <b>38 cancellations</b> in May, down 12% from April. Most were on lower-commitment plans:</div>
          {[['Digital Monthly', 24, '#E0455E'],['Student Digital', 9, '#F59E0B'],['Print + Digital', 5, '#14B8A6']].map(([l,v,c]) => (
            <div key={l} style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 10 }}>
              <div style={{ flex: '0 0 130px', color: '#5E6B7E' }}>{l}</div>
              <div style={{ flex: 1, height: 7, background: '#EEF1F4', borderRadius: 4 }}><div style={{ width: `${(v/24)*100}%`, height: '100%', background: c, borderRadius: 4 }} /></div>
              <div style={{ flex: '0 0 28px', textAlign: 'right', fontWeight: 700 }}>{v}</div>
            </div>
          ))}
          <div style={{ marginTop: 12, color: '#5E6B7E' }}>The top stated reason was <b>“too expensive”</b> (41%). Want me to draft a win-back offer for these customers?</div>
        </AIMsg>

        <UserMsg>Create an annual invoice for James Whitfield on the Print + Digital plan.</UserMsg>
        <AIMsg>
          <div style={{ marginBottom: 14 }}>Done — I’ve created a draft invoice. Review before sending:</div>
          <div style={{ border: '1px solid #EEF1F4', borderRadius: 12, padding: 16, background: '#FAFBFC' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}><span style={{ color: '#5E6B7E' }}>Customer</span><b>James Whitfield</b></div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}><span style={{ color: '#5E6B7E' }}>Plan</span><b>Print + Digital — Annual</b></div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}><span style={{ color: '#5E6B7E' }}>Amount</span><b>$299.00 CAD</b></div>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}><span style={{ color: '#5E6B7E' }}>Status</span><span style={{ background: '#FEF3C7', color: '#B45309', fontSize: 12, fontWeight: 700, padding: '3px 10px', borderRadius: 999 }}>Draft</span></div>
          </div>
          <div style={{ display: 'flex', gap: 10, marginTop: 14 }}>
            <button style={S.primaryBtn}>Send invoice</button>
            <button style={S.ghostBtn}>Edit</button>
          </div>
        </AIMsg>
      </div>

      <div style={{ position: 'sticky', bottom: 18, marginTop: 8, border: '1px solid #E6EBF0', borderRadius: 14, padding: '14px 16px', display: 'flex', alignItems: 'center', background: '#fff', boxShadow: '0 6px 20px -10px rgba(16,32,46,0.25)' }}>
        <span style={{ color: '#A6B0BD' }}>Ask anything about your data…</span>
        <button style={{ marginLeft: 'auto', width: 38, height: 38, borderRadius: 10, background: TEAL, color: '#fff', border: 'none', fontSize: 16 }}>➤</button>
      </div>
    </div>
  );
}

// — floating AI button —
function AIButton() {
  return <div style={{ position: 'fixed', bottom: 88, right: 24, width: 54, height: 54, borderRadius: 27, background: TEAL, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24, color: '#fff', boxShadow: '0 10px 24px -8px rgba(20,184,166,0.6)', zIndex: 800 }}>🧠</div>;
}

const S = {
  sidebar: { width: 272, flex: '0 0 272px', background: NAVY, display: 'flex', flexDirection: 'column', height: '100%' },
  navItem: { display: 'flex', alignItems: 'center', gap: 14, padding: '12px 14px', borderRadius: 10, fontSize: 16, color: '#C5CDD8', fontWeight: 500, cursor: 'pointer', marginBottom: 2 },
  navItemActive: { color: '#fff', fontWeight: 700, background: 'rgba(255,255,255,0.04)' },
  aiBadge: { background: '#1E3A8A', color: '#93C5FD', fontSize: 11, fontWeight: 800, padding: '2px 8px', borderRadius: 6 },
  subItem: { padding: '9px 14px 9px 50px', fontSize: 15, color: '#8A97A8', cursor: 'pointer', borderRadius: 8 },
  subItemActive: { color: TEAL, fontWeight: 700 },
  settingsBtn: { display: 'flex', alignItems: 'center', gap: 14, padding: '13px 16px', borderRadius: 12, border: '1px solid #243348', color: '#C5CDD8', fontWeight: 600, fontSize: 16, cursor: 'pointer' },
  topbar: { height: 72, background: NAVY, display: 'flex', alignItems: 'center', padding: '0 28px', gap: 16, flex: '0 0 72px' },
  siteSwitch: { display: 'flex', alignItems: 'center', gap: 8, border: '1px solid #243348', borderRadius: 10, padding: '9px 16px', color: '#fff', fontWeight: 600, fontSize: 15 },
  helpBtn: { width: 34, height: 34, borderRadius: 17, border: '1px solid #243348', color: '#8A97A8', display: 'flex', alignItems: 'center', justifyContent: 'center' },
  userAvatar: { width: 38, height: 38, borderRadius: 19, background: 'linear-gradient(135deg,#475569,#334155)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700 },
  page: { padding: '34px 40px 60px' },
  dateRange: { display: 'inline-flex', alignItems: 'center', gap: 10, background: '#fff', border: '1px solid #E6EBF0', borderRadius: 12, padding: '12px 18px', fontSize: 15, marginBottom: 24, boxShadow: '0 1px 2px rgba(16,32,46,0.04)' },
  kpiRow: { display: 'flex', background: '#fff', borderRadius: 16, border: '1px solid #EBEFF3', boxShadow: '0 1px 3px rgba(16,32,46,0.05)', marginBottom: 24, overflow: 'hidden' },
  kpi: { flex: 1, padding: '22px 22px 24px', minWidth: 0 },
  panel: { background: '#fff', borderRadius: 16, border: '1px solid #EBEFF3', boxShadow: '0 1px 3px rgba(16,32,46,0.05)', padding: '26px 28px' },
  searchRow: { display: 'flex', alignItems: 'center', gap: 14, background: '#fff', border: '1px solid #E6EBF0', borderRadius: 14, padding: '16px 18px', marginBottom: 22, boxShadow: '0 1px 3px rgba(16,32,46,0.04)' },
  selectBox: { display: 'flex', alignItems: 'center', gap: 30, border: '1px solid #E6EBF0', borderRadius: 10, padding: '12px 16px', color: INK, fontWeight: 500, minWidth: 140, justifyContent: 'space-between' },
  searchInput: { flex: 1, display: 'flex', alignItems: 'center', gap: 10, border: '1px solid #E6EBF0', borderRadius: 10, padding: '12px 16px' },
  searchBtn: { background: TEAL, color: '#fff', border: 'none', borderRadius: 10, padding: '0 18px', height: 46, fontSize: 16, cursor: 'pointer' },
  filterBtn: { background: '#fff', border: '1px solid #E6EBF0', borderRadius: 10, padding: '0 18px', height: 46, color: INK, fontWeight: 600, cursor: 'pointer' },
  ghostBtn: { background: '#fff', border: '1px solid #E6EBF0', borderRadius: 10, padding: '10px 16px', color: INK, fontWeight: 600, fontSize: 14, cursor: 'pointer' },
  primaryBtn: { background: TEAL, color: '#fff', border: 'none', borderRadius: 10, padding: '11px 18px', fontWeight: 700, fontSize: 14, cursor: 'pointer' },
  tableCard: { background: '#fff', borderRadius: 16, border: '1px solid #EBEFF3', boxShadow: '0 1px 3px rgba(16,32,46,0.05)', padding: '4px 24px' },
  tr: { display: 'flex', alignItems: 'center', padding: '18px 0', fontSize: 15 },
  custAvatar: { width: 36, height: 36, borderRadius: 18, background: '#EAFBF7', color: TEAL, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14 },
  detailCard: { background: '#fff', borderRadius: 16, border: '1px solid #EBEFF3', boxShadow: '0 1px 3px rgba(16,32,46,0.05)', padding: 28 },
  statCard: { border: '1px solid #EBEFF3', borderRadius: 14, padding: '18px 20px' },
};

// ============================================================
// VENDORS (Payable)
// ============================================================
const VENDORS = [
  { n: 'Daniel Okoro', e: 'daniel.okoro@gmail.com', p: '4165582019' },
  { n: 'Emily Carter', e: 'emily.carter@outlook.com', p: '6478840221' },
  { n: 'Natasha Romanenko', e: 'natasha.romanenko@gmail.com', p: '5149930044' },
  { n: 'Hassan Idris', e: 'hassan.idris@gmail.com', p: '6135561180' },
  { n: 'Marco Pereira', e: 'marco.pereira@gmail.com', p: '5198840021' },
];
const VAVA = ['#14B8A6','#10B981','#0EA5A4','#0D9488','#14B8A6'];
function VendorsView({ tourRefs }) {
  return (
    <div style={S.page}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <PageTitle crumbs={['Home', 'Payable', 'Vendors']}>Vendors</PageTitle>
        <span style={{ color: TEAL, fontWeight: 600, fontSize: 14, display: 'flex', alignItems: 'center', gap: 6 }}>▭ Docs</span>
      </div>
      <div style={S.searchRow}>
        <div style={S.selectBox}>First Name <span style={{ color: '#8A97A8' }}>⌄</span></div>
        <span style={{ color: '#8A97A8', fontWeight: 600 }}>IN</span>
        <div style={{ ...S.searchInput, flex: '0 1 200px' }}>🔍 <span style={{ color: '#A6B0BD' }}>Se…</span></div>
        <button style={S.searchBtn}>🔍</button>
        <button style={S.filterBtn}>⚙ Filter</button>
        <button style={S.ghostBtn}>▣ Export Payment Batch <span style={{ background: '#DBEAFE', color: '#2563EB', fontSize: 10, fontWeight: 700, padding: '2px 7px', borderRadius: 6, marginLeft: 4 }}>Beta</span></button>
        <button style={S.ghostBtn}>⤓ Export</button>
        <button style={S.primaryBtn} ref={el => { if (tourRefs) tourRefs.current['create-vendor'] = el; }}>+ Create Vendor</button>
      </div>
      <div style={S.tableCard} ref={el => { if (tourRefs) tourRefs.current['vendors-table'] = el; }}>
        <div style={{ ...S.tr, color: '#8A97A8', fontSize: 12, letterSpacing: '.05em', fontWeight: 700, borderBottom: '1px solid #EEF1F4' }}>
          <div style={{ flex: 2.2 }}>NAME</div><div style={{ flex: 2.4 }}>EMAIL</div><div style={{ flex: 1.2 }}>PHONE</div><div style={{ flex: 1 }}>BILLS</div><div style={{ flex: 1 }}>TOTAL BILL</div><div style={{ flex: 0.6, textAlign: 'right' }}>ACTIONS</div>
        </div>
        {VENDORS.map((v, i) => (
          <div key={i} style={{ ...S.tr, borderBottom: i < VENDORS.length-1 ? '1px solid #F1F4F7' : 'none' }}>
            <div style={{ flex: 2.2, display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ ...S.custAvatar, background: VAVA[i % VAVA.length], color: '#fff', borderRadius: 8 }}>{v.n.split(' ').map(w=>w[0]).slice(0,2).join('').toUpperCase()}</div>
              <span style={{ fontWeight: 600, color: INK }}>{v.n}</span>
            </div>
            <div style={{ flex: 2.4, color: TEAL }}>{v.e}</div>
            <div style={{ flex: 1.2, color: '#5E6B7E' }}>{v.p}</div>
            <div style={{ flex: 1 }}><span style={{ background: '#EFF6FF', color: '#2563EB', fontSize: 12, fontWeight: 600, padding: '4px 12px', borderRadius: 999 }}>0 bills</span></div>
            <div style={{ flex: 1, color: '#16A34A', fontWeight: 700 }}>$0.00</div>
            <div style={{ flex: 0.6, textAlign: 'right', color: '#A6B0BD' }}>•••</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============================================================
// PRODUCTS LIST
// ============================================================
const PRODUCTS = [
  { id: 19, n: 'All-Access Annual', int: 'all_access_annual', plans: 4, color: '#14B8A6' },
  { id: 26, n: 'Digital Monthly', int: 'digital_monthly', plans: 3, color: '#1E3A8A', initials: 'DM' },
  { id: 20, n: 'Print + Digital', int: 'print_digital_bundle', plans: 5, color: '#E0455E' },
  { id: 295, n: 'Student Digital', int: 'student_digital', plans: 2, color: '#64748B' },
];
function ProductsView({ tourRefs, onCreate }) {
  return (
    <div style={S.page}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <PageTitle crumbs={['Home', 'Products']}>Products</PageTitle>
        <span style={{ color: TEAL, fontWeight: 600, fontSize: 14, display: 'flex', alignItems: 'center', gap: 6 }}>▭ Docs</span>
      </div>
      <div style={S.searchRow}>
        <div style={S.selectBox}>All <span style={{ color: '#8A97A8' }}>⌄</span></div>
        <div style={S.searchInput}>🔍 <span style={{ color: '#A6B0BD' }}>Search…</span></div>
        <button style={S.ghostBtn}>⤓ Export All</button>
        <button style={S.primaryBtn} ref={el => { if (tourRefs) tourRefs.current['new-product'] = el; }} onClick={onCreate}>+ New</button>
      </div>
      <div style={{ display: 'flex', gap: 28, borderBottom: '1px solid #E6EBF0', marginBottom: 6 }}>
        {[['All',23,true],['Active',22],['Archived',1]].map(([l,c,a]) => (
          <div key={l} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '0 2px 12px', fontWeight: a ? 700 : 500, color: a ? INK : '#5E6B7E', borderBottom: a ? `3px solid ${TEAL}` : '3px solid transparent' }}>
            {l} <span style={{ background: a ? '#DCFCE7' : '#EEF1F4', color: a ? '#16A34A' : '#5E6B7E', fontSize: 12, fontWeight: 700, padding: '2px 9px', borderRadius: 999 }}>{c}</span>
          </div>
        ))}
      </div>
      <div style={S.tableCard} ref={el => { if (tourRefs) tourRefs.current['products-table'] = el; }}>
        <div style={{ ...S.tr, color: '#8A97A8', fontSize: 12, letterSpacing: '.05em', fontWeight: 700, borderBottom: '1px solid #EEF1F4' }}>
          <div style={{ flex: 0.6 }}>ID ⇅</div><div style={{ flex: 2.4 }}>NAME ⇅</div><div style={{ flex: 2 }}>INTERNAL NAME ⇅</div><div style={{ flex: 1 }}>PLANS</div><div style={{ flex: 1 }}>ADDRESS ⇅</div><div style={{ flex: 0.6, textAlign: 'right' }}>STATUS</div>
        </div>
        {PRODUCTS.map((p, i) => (
          <div key={i} style={{ ...S.tr, borderBottom: i < PRODUCTS.length-1 ? '1px solid #F1F4F7' : 'none' }}>
            <div style={{ flex: 0.6, color: TEAL, fontWeight: 600 }}>{p.id}</div>
            <div style={{ flex: 2.4, display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ width: 40, height: 40, borderRadius: 8, background: p.color, color: '#fff', fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13 }}>{p.initials || p.n.slice(0,2).toUpperCase()}</div>
              <span style={{ fontWeight: 600, color: INK }}>{p.n}</span>
            </div>
            <div style={{ flex: 2, color: '#5E6B7E' }}>{p.int}</div>
            <div style={{ flex: 1, color: '#5E6B7E' }}>{p.plans} plans</div>
            <div style={{ flex: 1 }}><span style={{ background: '#EFF6FF', color: '#2563EB', fontSize: 12, fontWeight: 600, padding: '4px 12px', borderRadius: 999 }}>● Required</span></div>
            <div style={{ flex: 0.6, textAlign: 'right', color: '#A6B0BD' }}>•••</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============================================================
// CREATE PRODUCT
// ============================================================
function CreateProductView({ tourRefs, onBack }) {
  const fields = [
    ['Product name', true, 'e.g. Digital Membership'],
    ['Product internal name', false, 'internal_reference_name'],
    ['Product description', false, 'Describe what this product includes'],
    ['Entitlements', false, 'Select entitlements'],
    ['Statement descriptor', false, 'Appears on customer statements'],
    ['Available on the following sites', true, 'Select sites'],
    ['Product only available in the following countries', false, 'All countries'],
  ];
  return (
    <div style={S.page}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, color: '#5E6B7E', fontSize: 14, marginBottom: 22 }}>
        <span onClick={onBack} style={{ cursor: 'pointer' }}>Products</span><span style={{ color: '#C2CBD6' }}>/</span><b style={{ color: INK }}>Create</b>
      </div>
      <div style={{ maxWidth: 1080, margin: '0 auto', background: '#fff', borderRadius: 16, border: '1px solid #EBEFF3', boxShadow: '0 1px 3px rgba(16,32,46,0.06)', overflow: 'hidden' }}
        ref={el => { if (tourRefs) tourRefs.current['create-product-card'] = el; }}>
        <div style={{ background: TEAL, padding: '24px 32px', fontSize: 24, fontWeight: 800, color: '#fff' }}>Create a product</div>
        <div style={{ padding: '12px 32px 28px' }}>
          {fields.map(([label, req, ph], i) => (
            <div key={i} style={{ padding: '22px 0', borderBottom: '1px solid #F1F4F7' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: '#5E6B7E', fontSize: 15, marginBottom: 14 }}>
                {label}{req && <span style={{ color: '#E0455E' }}>*</span>} <span style={{ width: 16, height: 16, borderRadius: 8, background: '#C2CBD6', color: '#fff', fontSize: 11, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>i</span>
              </div>
              <input placeholder={ph} style={{ width: '100%', border: 'none', borderBottom: '1px solid #E6EBF0', padding: '8px 0', fontSize: 15, color: INK, outline: 'none', background: 'transparent' }} />
            </div>
          ))}
          <div style={{ display: 'flex', gap: 12, marginTop: 24, justifyContent: 'flex-end' }}>
            <button style={S.ghostBtn} onClick={onBack}>Cancel</button>
            <button style={S.primaryBtn}>Create product</button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Sidebar, TopBar, OverviewView, CustomersView, CustomerDetailView, AIAgentView, AIButton, PelcroLogo, VendorsView, ProductsView, CreateProductView });
