// Businesses — agency-mode client management
const BUSINESSES = [
  { id: 'b1', name: 'Demiurge Systems', logo: 'DS', status: 'active', mrr: 390, profit: 377, usage: 13, margin: 97, products: 2, sinceMonths: 2, web: 'demiurge.systems', calls7d: 0, paid: 0, ownerEmail: null, invited: false, phone: null, kb: 0, hours: true },
  { id: 'b2', name: 'Headonizm Hair', logo: 'HH', status: 'active', mrr: 240, profit: 218, usage: 22, margin: 91, products: 2, sinceMonths: 4, web: 'headonizm.co.uk', calls7d: 142, paid: 720, ownerEmail: 'sasha@headonizm.co.uk', invited: true, phone: '+44 20 4538 0188', kb: 12, hours: true },
  { id: 'b3', name: 'Precision Barbers', logo: 'PB', status: 'active', mrr: 320, profit: 296, usage: 24, margin: 92, products: 3, sinceMonths: 6, web: 'precision-barbers.co.uk', calls7d: 218, paid: 1640, ownerEmail: 'tom@precision-barbers.co.uk', invited: true, phone: '+44 161 873 4421', kb: 24, hours: true },
  { id: 'b4', name: 'The Laughing Halibut', logo: 'LH', status: 'setup', mrr: 0, profit: 0, usage: 0, margin: 0, products: 1, sinceMonths: 1, web: 'thelaughinghalibut.co.uk', calls7d: 0, paid: 0, ownerEmail: 'phil@thelaughinghalibut.co.uk', invited: true, phone: null, kb: 4, hours: false },
  { id: 'b5', name: 'Shop & Donate', logo: 'SD', status: 'paused', mrr: 0, profit: 0, usage: 0, margin: 0, products: 1, sinceMonths: 3, web: 'shopanddonate.org', calls7d: 0, paid: 380, ownerEmail: 'admin@shopanddonate.org', invited: true, phone: '+44 20 3514 6622', kb: 8, hours: true },
];

Object.assign(window, { BUSINESSES });

function Businesses() {
  const [selected, setSelected] = React.useState(null);
  if (selected) return <BusinessDetail id={selected} onBack={() => setSelected(null)}/>;
  return <BusinessesList onSelect={setSelected}/>;
}

function BusinessesList({ onSelect }) {
  const totalMRR = BUSINESSES.reduce((s, b) => s + b.mrr, 0);
  const totalProfit = BUSINESSES.reduce((s, b) => s + b.profit, 0);
  const totalUsage = BUSINESSES.reduce((s, b) => s + b.usage, 0);
  const active = BUSINESSES.filter(b => b.status === 'active').length;

  return (
    <div>
      <div className="page-hd">
        <div className="page-hd-l">
          <div className="page-eyebrow">Agency · {BUSINESSES.length} client businesses · {active} active</div>
          <h1 className="page-title">Businesses</h1>
          <div className="page-sub">Every client account you operate AI for. Pricing, usage, and profit — one row each.</div>
        </div>
        <div className="page-hd-r">
          <button className="btn"><Icon.Filter className="icon"/>Filter</button>
          <button className="btn primary"><Icon.Plus className="icon"/>Add business</button>
        </div>
      </div>

      <div style={{ padding: 24, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
        <KpiBlock label="MRR · ACROSS BOOK" val={totalMRR} unit="£" delta="+£190" stream={fakeStream(50, 14, 60, 20)}/>
        <KpiBlock label="MONTHLY PROFIT" val={totalProfit} unit="£" delta="+£166" stream={fakeStream(51, 14, 55, 18)}/>
        <KpiBlock label="USAGE COST · MTD" val={totalUsage} unit="£" delta="-12%" deltaGood stream={fakeStream(52, 14, 30, 12)}/>
        <KpiBlock label="ACTIVE BUSINESSES" val={active} delta="+1" stream={fakeStream(53, 14, 3, 2)}/>
      </div>

      <div style={{ padding: '0 24px 24px' }}>
        <div className="panel">
          <div className="panel-hd">
            <h3>Your book</h3>
            <span className="panel-meta">{BUSINESSES.length} businesses · {active} active</span>
          </div>
          <table className="dem">
            <thead>
              <tr>
                <th>Business</th><th>Status</th><th>Products</th><th>MRR</th><th>Usage</th>
                <th>Profit</th><th>Margin</th><th>Health</th><th></th>
              </tr>
            </thead>
            <tbody>
              {BUSINESSES.map(b => {
                const health = b.status === 'paused' ? { l: 'Inactive', c: 'var(--text-faint)' }
                  : !b.phone ? { l: 'Needs setup', c: 'var(--warn)' }
                  : b.calls7d === 0 ? { l: 'No recent calls', c: 'var(--warn)' }
                  : { l: 'Healthy', c: 'var(--good)' };
                return (
                  <tr key={b.id} onClick={() => onSelect(b.id)}>
                    <td>
                      <div className="row" style={{ gap: 12 }}>
                        <div style={{ width: 34, height: 34, borderRadius: 8, background: 'linear-gradient(135deg, rgba(139, 107, 255, 0.3), rgba(75, 232, 255, 0.18))', border: '1px solid var(--border)', display: 'grid', placeItems: 'center', fontSize: 11, fontFamily: 'var(--font-mono)', fontWeight: 600 }}>{b.logo}</div>
                        <div>
                          <div>{b.name}</div>
                          <div className="dim mono" style={{ fontSize: 10 }}>{b.web} · {b.sinceMonths}mo</div>
                        </div>
                      </div>
                    </td>
                    <td><StatusTag status={b.status === 'setup' ? 'scheduled' : b.status === 'paused' ? 'paused' : 'live'}/></td>
                    <td className="num">{b.products}</td>
                    <td className="num">£{b.mrr}</td>
                    <td className="num">£{b.usage}</td>
                    <td className="num" style={{ color: b.profit > 0 ? 'var(--cyan)' : 'var(--text-faint)' }}>£{b.profit}</td>
                    <td>
                      <div className="row" style={{ gap: 8 }}>
                        <span className="mono tnum" style={{ minWidth: 30, color: b.margin > 90 ? 'var(--good)' : 'var(--text-dim)' }}>{b.margin}%</span>
                        <div className="bar-track" style={{ width: 60 }}>
                          <div className="bar-fill flat" style={{ width: `£${b.margin}%`, background: b.margin > 90 ? 'var(--good)' : 'var(--violet)' }}/>
                        </div>
                      </div>
                    </td>
                    <td>
                      <span className="row" style={{ gap: 6, fontSize: 11 }}>
                        <span style={{ width: 6, height: 6, borderRadius: '50%', background: health.c, boxShadow: `0 0 6px ${health.c}` }}/>
                        {health.l}
                      </span>
                    </td>
                    <td><Icon.ChevronR style={{ width: 14, height: 14, color: 'var(--text-faint)' }}/></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      <div style={{ padding: '0 24px 24px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <div className="panel">
          <div className="panel-hd">
            <h3><Icon.Trophy style={{ width: 14, height: 14, color: 'var(--warn)' }}/>Partner progression</h3>
            <span className="mono" style={{ fontSize: 10, color: 'var(--warn)' }}>BRONZE PARTNER</span>
          </div>
          <div className="panel-body" style={{ display: 'flex', gap: 18 }}>
            <Ring pct={33} size={72} stroke={6}/>
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 8 }}>
              <div className="row" style={{ justifyContent: 'space-between' }}>
                <span className="serif" style={{ fontSize: 18, fontStyle: 'italic' }}>2 / 6 milestones</span>
                <span className="mono dim" style={{ fontSize: 11 }}>NEXT: SILVER</span>
              </div>
              <div className="dim" style={{ fontSize: 12 }}>Hit £1,000 MRR and 5 active businesses to unlock Silver — white-label branding, reduced platform fees, dedicated CSM.</div>
              <div className="bar-track" style={{ marginTop: 4 }}>
                <div className="bar-fill" style={{ width: '33%' }}/>
              </div>
            </div>
          </div>
        </div>

        <div className="panel">
          <div className="panel-hd"><h3>Revenue goal</h3></div>
          <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <div className="row" style={{ justifyContent: 'space-between', alignItems: 'baseline' }}>
              <span className="serif" style={{ fontSize: 32, fontStyle: 'italic' }}>£{totalMRR}</span>
              <span className="mono dim">/ £1,000/mo goal</span>
            </div>
            <div className="bar-track" style={{ height: 8 }}>
              <div className="bar-fill" style={{ width: `£${(totalMRR / 1000) * 100}%` }}/>
            </div>
            <div className="row" style={{ justifyContent: 'space-between', fontSize: 11 }}>
              <span className="mono dim">{Math.round((totalMRR / 1000) * 100)}% of goal</span>
              <span className="mono" style={{ color: 'var(--cyan)' }}>+£190 this month</span>
            </div>
            <button className="btn ghost sm" style={{ alignSelf: 'flex-start', marginTop: 6 }}>Adjust goal <Icon.ChevronR className="icon" style={{ width: 12, height: 12 }}/></button>
          </div>
        </div>
      </div>
    </div>
  );
}

function BusinessDetail({ id, onBack }) {
  const b = BUSINESSES.find(x => x.id === id);
  const [tab, setTab] = React.useState('overview');
  const [aiReceptionPrice, setAiReceptionPrice] = React.useState(b.mrr);
  const [usageMin, setUsageMin] = React.useState(500);
  const usageRate = 0.026; // £/min
  const estUsage = (usageMin * usageRate);
  const profit = aiReceptionPrice - estUsage;
  const margin = aiReceptionPrice > 0 ? Math.round((profit / aiReceptionPrice) * 100) : 0;

  const tabs = [
    { id: 'overview', label: 'Overview' },
    { id: 'reception', label: 'AI Receptionist' },
    { id: 'website', label: 'Website Builder' },
    { id: 'proposal', label: 'Send Proposal' },
  ];

  return (
    <div>
      <div className="page-hd">
        <div className="page-hd-l">
          <button className="btn ghost sm" onClick={onBack} style={{ alignSelf: 'flex-start', padding: '4px 10px 4px 8px' }}>
            <Icon.ChevronR style={{ width: 12, height: 12, transform: 'rotate(180deg)' }}/>All businesses
          </button>
          <div className="row" style={{ gap: 14, marginTop: 8 }}>
            <div style={{ width: 56, height: 56, borderRadius: 12, background: 'linear-gradient(135deg, rgba(139, 107, 255, 0.35), rgba(75, 232, 255, 0.22))', border: '1px solid rgba(139, 107, 255, 0.3)', display: 'grid', placeItems: 'center', fontSize: 18, fontFamily: 'var(--font-mono)', fontWeight: 700 }}>{b.logo}</div>
            <div>
              <div className="row" style={{ gap: 10, marginBottom: 4 }}>
                <h1 className="serif" style={{ margin: 0, fontSize: 32, fontStyle: 'italic', fontWeight: 400 }}>{b.name}</h1>
                <StatusTag status={b.status === 'paused' ? 'paused' : b.status === 'setup' ? 'scheduled' : 'live'}/>
              </div>
              <div className="page-eyebrow" style={{ letterSpacing: '0.14em' }}>Revenue command center · {b.web} · client for {b.sinceMonths} months</div>
            </div>
          </div>
        </div>
        <div className="page-hd-r">
          <button className="btn"><Icon.Mail className="icon"/>Email owner</button>
          <button className="btn primary"><Icon.Sparkles className="icon"/>Send proposal</button>
        </div>
      </div>

      <div style={{ padding: '16px 24px 0', display: 'flex', gap: 4, borderBottom: '1px solid var(--border)' }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: '10px 16px',
            fontSize: 13,
            color: tab === t.id ? 'var(--text)' : 'var(--text-dim)',
            borderBottom: tab === t.id ? '2px solid var(--violet)' : '2px solid transparent',
            marginBottom: -1,
          }}>{t.label}</button>
        ))}
      </div>

      {tab === 'overview' && (
        <React.Fragment>
          <div style={{ padding: 24, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
            <ProfitCard label="YOUR MONTHLY PROFIT" val={profit.toFixed(2)} unit="£" sub={`£${margin}% margin · ${b.products} products active`} accent/>
            <KpiBlock label="MRR · THIS BUSINESS" val={aiReceptionPrice} unit="£" delta="+£0" stream={fakeStream(60, 14, 40, 8)}/>
            <KpiBlock label="EST. USAGE · MTD" val={estUsage.toFixed(2)} unit="£" delta="—" stream={fakeStream(61, 14, 12, 4)}/>
            <KpiBlock label="ANNUAL PROJECTION" val={(profit * 12).toFixed(0)} unit="£" delta="+£0" stream={fakeStream(62, 14, 360, 40)}/>
          </div>

          <div style={{ padding: '0 24px 14px', display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 14 }}>
            <div className="col" style={{ gap: 14 }}>
              <div className="panel">
                <div className="panel-hd">
                  <h3>Products &amp; revenue</h3>
                  <span className="panel-meta">{b.products} of 2 active</span>
                </div>
                <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                  <ProductCard
                    name="AI Receptionist"
                    sub="24/7 inbound call handling, booking, message-taking"
                    icon="Phone"
                    status="live"
                    accent="var(--cyan)"
                    price={aiReceptionPrice}
                    onPrice={setAiReceptionPrice}
                    usageMin={usageMin}
                    onUsage={setUsageMin}
                    usageRate={usageRate}
                    estUsage={estUsage}
                    profit={profit}
                  />
                  <ProductCard
                    name="Website Builder"
                    sub="AI-generated landing page with booking widget"
                    icon="Globe"
                    status="preview"
                    accent="var(--violet)"
                    isPreview
                  />
                </div>
              </div>

              <div className="panel">
                <div className="panel-hd"><h3>Total from this client</h3></div>
                <div className="panel-body" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 18 }}>
                  <TotalStat label="PRODUCTS" val={`£${b.products} active`}/>
                  <TotalStat label="REVENUE" val={`£${aiReceptionPrice}/mo`}/>
                  <TotalStat label="USAGE" val={`£${estUsage.toFixed(2)}/mo`}/>
                  <TotalStat label="PROFIT" val={`£${profit.toFixed(2)}/mo`} accent/>
                </div>
              </div>
            </div>

            <div className="col" style={{ gap: 14 }}>
              <div className="panel">
                <div className="panel-hd">
                  <h3>Last 7 days · calls</h3>
                  <span className="mono dim" style={{ fontSize: 11 }}>{b.calls7d > 0 ? `£${b.calls7d} calls` : 'no calls'}</span>
                </div>
                <div className="panel-body">
                  {b.calls7d > 0 ? (
                    <React.Fragment>
                      <Sparkline data={fakeStream(b.id.charCodeAt(1), 14, 14, 10)} w={260} h={60} gradient/>
                      <div className="row" style={{ marginTop: 10, justifyContent: 'space-between', fontSize: 11 }}>
                        <span className="mono dim">AI handled · 88%</span>
                        <span className="mono" style={{ color: 'var(--cyan)' }}>avg 2m 14s</span>
                      </div>
                    </React.Fragment>
                  ) : (
                    <EmptyState
                      icon="Phone"
                      ttl="No calls yet"
                      sub="Calls will appear here once a phone number is provisioned and the AI receptionist goes live."
                    />
                  )}
                </div>
              </div>

              <div className="panel">
                <div className="panel-hd">
                  <h3>Payment history</h3>
                  <span className="mono" style={{ fontSize: 12, color: b.paid > 0 ? 'var(--cyan)' : 'var(--text-faint)' }}>£{b.paid}</span>
                </div>
                <div className="panel-body">
                  {b.paid > 0 ? (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                      {[1, 2, 3].map(i => (
                        <div key={i} className="row" style={{ justifyContent: 'space-between', padding: '8px 10px', background: 'rgba(0,0,0,0.2)', border: '1px solid var(--border)', borderRadius: 'var(--radius)', fontSize: 12 }}>
                          <span className="mono dim">{1 + i} {['Apr', 'Mar', 'Feb'][i - 1]} 2026</span>
                          <span className="mono">£{(b.paid / 3).toFixed(0)}</span>
                          <span className="tag live">PAID</span>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <EmptyState
                      icon="Database"
                      ttl="No payments yet"
                      sub="When this client pays you, charges land here automatically via Stripe."
                    />
                  )}
                </div>
              </div>
            </div>
          </div>

          <div style={{ padding: '0 24px 24px' }}>
            <div className="panel">
              <div className="panel-hd">
                <h3>Business details</h3>
                <span className="panel-meta">setup status · 6 of 8 complete</span>
              </div>
              <div className="panel-body" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
                <DetailRow label="WEBSITE" val={b.web} status="set"/>
                <DetailRow label="OWNER EMAIL" val={b.ownerEmail || 'Not set'} status={b.ownerEmail ? 'set' : 'missing'}/>
                <DetailRow label="INVITATION" val={b.invited ? 'Invited · pending' : 'Not invited'} status={b.invited ? 'pending' : 'missing'}/>
                <DetailRow label="AI PHONE NUMBER" val={b.phone || 'Not provisioned'} status={b.phone ? 'set' : 'missing'}/>
                <DetailRow label="BUSINESS PHONE" val={b.phone ? b.phone.replace(/(\+44 \d+ \d+) /, '$1 ') : 'Not set'} status={b.phone ? 'set' : 'missing'}/>
                <DetailRow label="KNOWLEDGE BASE" val={`£${b.kb} items`} status={b.kb > 0 ? 'set' : 'missing'}/>
                <DetailRow label="BUSINESS HOURS" val={b.hours ? 'Configured' : 'Not configured'} status={b.hours ? 'set' : 'missing'}/>
                <DetailRow label="BILLING" val={b.status === 'active' ? 'Active' : b.status === 'paused' ? 'Paused' : 'Pending'} status={b.status === 'active' ? 'set' : 'pending'}/>
              </div>
            </div>
          </div>

          <div style={{ padding: '0 24px 28px' }}>
            <div className="panel" style={{ borderColor: 'rgba(255, 93, 110, 0.2)' }}>
              <div className="panel-hd">
                <h3 style={{ color: 'var(--danger)' }}>Danger zone</h3>
              </div>
              <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                <DangerRow t="Pause this business" sub="Stop billing the client and pause all AI products. Data preserved." cta="Pause"/>
                <DangerRow t="Transfer ownership" sub="Hand this business off to another partner in your network." cta="Transfer"/>
                <DangerRow t="Delete business" sub="Removes the business and all its data permanently. Cannot be undone." cta="Delete" red/>
              </div>
            </div>
          </div>
        </React.Fragment>
      )}

      {tab === 'reception' && <ReceptionTab business={b}/>}
      {tab === 'website' && <WebsiteTab business={b}/>}
      {tab === 'proposal' && <ProposalTab business={b}/>}
    </div>
  );
}

function ProfitCard({ label, val, unit, sub, accent }) {
  return (
    <div className="kpi-block" style={accent ? { border: '1px solid rgba(75, 232, 255, 0.3)', background: 'linear-gradient(135deg, rgba(75, 232, 255, 0.05), rgba(139, 107, 255, 0.05))' } : {}}>
      <div className="kpi-label" style={accent ? { color: 'var(--cyan)' } : {}}>{label}</div>
      <div className="kpi-val">
        <span className="unit">£</span>{val}<span className="unit" style={{ fontSize: 18 }}>/mo</span>
      </div>
      <div className="kpi-meta">
        <span className="faint">{sub}</span>
      </div>
    </div>
  );
}

function ProductCard({ name, sub, icon, status, accent, price, onPrice, usageMin, onUsage, usageRate, estUsage, profit, isPreview }) {
  const I = Icon[icon] || Icon.Bolt;
  return (
    <div style={{
      padding: 18,
      border: '1px solid var(--border)',
      borderRadius: 'var(--radius-lg)',
      background: 'rgba(0, 0, 0, 0.2)',
      position: 'relative',
      overflow: 'hidden',
    }}>
      <div className="row" style={{ justifyContent: 'space-between', marginBottom: 14 }}>
        <div className="row" style={{ gap: 12 }}>
          <div style={{ width: 38, height: 38, borderRadius: 10, background: `£${accent}22`, border: `1px solid ${accent}44`, display: 'grid', placeItems: 'center' }}>
            <I style={{ width: 18, height: 18, color: accent }}/>
          </div>
          <div>
            <div className="row" style={{ gap: 8 }}>
              <span style={{ fontSize: 15, fontWeight: 500 }}>{name}</span>
              {isPreview ? <span className="tag violet">PREVIEW</span> : <StatusTag status={status}/>}
            </div>
            <span className="dim" style={{ fontSize: 12 }}>{sub}</span>
          </div>
        </div>
        {!isPreview && (
          <div style={{ textAlign: 'right' }}>
            <div className="serif" style={{ fontSize: 22, fontStyle: 'italic', color: accent }}>£{price}/mo</div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--cyan)' }}>+£{profit.toFixed(0)} profit/mo</div>
          </div>
        )}
        {isPreview && (
          <div style={{ textAlign: 'right' }}>
            <div className="serif dim" style={{ fontSize: 22, fontStyle: 'italic' }}>£0/mo</div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--text-faint)' }}>+£0 profit/mo</div>
          </div>
        )}
      </div>

      {!isPreview ? (
        <React.Fragment>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 14 }}>
            <div>
              <div className="mono faint" style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 6 }}>Monthly price</div>
              <div className="row" style={{ gap: 8 }}>
                <span className="mono dim" style={{ fontSize: 14 }}>£</span>
                <input
                  type="number"
                  value={price}
                  onChange={e => onPrice(parseInt(e.target.value) || 0)}
                  style={{
                    padding: '6px 10px',
                    background: 'rgba(0, 0, 0, 0.4)',
                    border: '1px solid var(--border)',
                    borderRadius: 'var(--radius)',
                    fontFamily: 'var(--font-mono)',
                    fontSize: 14,
                    width: 90,
                    color: 'var(--text)',
                  }}
                />
                <span className="mono dim" style={{ fontSize: 12 }}>/mo</span>
              </div>
            </div>
            <div>
              <div className="mono faint" style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 6 }}>Est. usage cost</div>
              <div className="row" style={{ gap: 8 }}>
                <span className="serif" style={{ fontSize: 22, fontStyle: 'italic', color: 'var(--warn)' }}>£{estUsage.toFixed(2)}</span>
                <span className="mono dim" style={{ fontSize: 11 }}>at £{usageRate}/min</span>
              </div>
            </div>
          </div>

          <div>
            <div className="row" style={{ justifyContent: 'space-between', marginBottom: 8 }}>
              <span className="mono faint" style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em' }}>Estimated monthly usage</span>
              <span className="mono" style={{ fontSize: 12, color: 'var(--text)' }}>{usageMin.toLocaleString()} min</span>
            </div>
            <input
              type="range"
              min={0}
              max={5000}
              step={50}
              value={usageMin}
              onChange={e => onUsage(parseInt(e.target.value))}
              style={{
                width: '100%',
                accentColor: 'var(--violet)',
                height: 4,
              }}
            />
            <div className="row" style={{ justifyContent: 'space-between', fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--text-faint)', marginTop: 4 }}>
              <span>0 min</span>
              <span>1,000</span>
              <span>2,500</span>
              <span>5,000 min</span>
            </div>
          </div>

          <div className="row" style={{ gap: 8, marginTop: 14, paddingTop: 14, borderTop: '1px solid var(--border)' }}>
            <button className="btn primary sm">Open AI Receptionist <Icon.ChevronR className="icon" style={{ width: 12, height: 12 }}/></button>
            <button className="btn sm">Adjust pricing</button>
            <button className="btn ghost sm" style={{ marginLeft: 'auto', color: 'var(--danger)' }}>Remove product</button>
          </div>
        </React.Fragment>
      ) : (
        <div className="row" style={{ paddingTop: 14, borderTop: '1px solid var(--border)', gap: 8 }}>
          <button className="btn sm">Enable preview <Icon.ChevronR className="icon" style={{ width: 12, height: 12 }}/></button>
          <button className="btn ghost sm" style={{ marginLeft: 'auto', color: 'var(--danger)' }}>Remove product</button>
        </div>
      )}
    </div>
  );
}

function TotalStat({ label, val, accent }) {
  return (
    <div>
      <div className="mono faint" style={{ fontSize: 10, letterSpacing: '0.12em', marginBottom: 6 }}>{label}</div>
      <div className="serif" style={{ fontSize: 22, fontStyle: 'italic', color: accent ? 'var(--cyan)' : 'var(--text)' }}>{val}</div>
    </div>
  );
}

function DetailRow({ label, val, status }) {
  const colors = {
    set: { dot: 'var(--good)', bg: 'rgba(93, 255, 176, 0.05)' },
    missing: { dot: 'var(--warn)', bg: 'rgba(255, 177, 75, 0.05)' },
    pending: { dot: 'var(--cyan)', bg: 'rgba(75, 232, 255, 0.05)' },
  };
  const c = colors[status] || colors.set;
  return (
    <div style={{
      padding: 14,
      background: c.bg,
      border: '1px solid var(--border)',
      borderRadius: 'var(--radius)',
      display: 'flex', flexDirection: 'column', gap: 4,
    }}>
      <div className="row" style={{ gap: 6 }}>
        <span style={{ width: 6, height: 6, borderRadius: '50%', background: c.dot, boxShadow: `0 0 4px ${c.dot}` }}/>
        <span className="mono faint" style={{ fontSize: 9, letterSpacing: '0.14em' }}>{label}</span>
      </div>
      <div style={{ fontSize: 13, color: status === 'missing' ? 'var(--text-dim)' : 'var(--text)' }}>{val}</div>
    </div>
  );
}

function DangerRow({ t, sub, cta, red }) {
  return (
    <div className="row" style={{ justifyContent: 'space-between', gap: 18 }}>
      <div>
        <div style={{ fontSize: 13, marginBottom: 4 }}>{t}</div>
        <div className="dim" style={{ fontSize: 11, lineHeight: 1.5 }}>{sub}</div>
      </div>
      <button className="btn" style={red ? { color: 'var(--danger)', borderColor: 'rgba(255, 93, 110, 0.3)' } : {}}>{cta}</button>
    </div>
  );
}

function EmptyState({ icon, ttl, sub }) {
  const I = Icon[icon] || Icon.Compass;
  return (
    <div style={{ padding: '24px 16px', textAlign: 'center' }}>
      <div style={{
        width: 40, height: 40, borderRadius: 10,
        background: 'rgba(255, 255, 255, 0.04)',
        border: '1px solid var(--border)',
        display: 'grid', placeItems: 'center',
        margin: '0 auto 10px',
      }}>
        <I style={{ width: 18, height: 18, color: 'var(--text-faint)' }}/>
      </div>
      <div style={{ fontSize: 13, color: 'var(--text)', marginBottom: 4 }}>{ttl}</div>
      <div className="dim" style={{ fontSize: 11, lineHeight: 1.5, maxWidth: 240, margin: '0 auto' }}>{sub}</div>
    </div>
  );
}

function ReceptionTab({ business: b }) {
  return (
    <div style={{ padding: 24, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
      <div className="panel">
        <div className="panel-hd"><h3>Greeting</h3></div>
        <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div className="mono faint" style={{ fontSize: 10, letterSpacing: '0.12em' }}>OPENING LINE</div>
          <div style={{ padding: 14, background: 'rgba(0, 0, 0, 0.25)', border: '1px solid var(--border)', borderRadius: 'var(--radius)', fontSize: 13, lineHeight: 1.5 }}>
            "Hi, you've reached {b.name}. I'm Helena, the AI assistant — how can I help you today?"
          </div>
          <div className="mono faint" style={{ fontSize: 10, letterSpacing: '0.12em' }}>VOICE</div>
          <div className="row">
            <select style={{ ...inputStyleB }}>
              <option>Helena · British English · warm</option>
              <option>Oliver · British English · neutral</option>
              <option>Sophia · British English · upbeat</option>
            </select>
            <button className="btn sm"><Icon.Play className="icon"/>Preview</button>
          </div>
        </div>
      </div>
      <div className="panel">
        <div className="panel-hd"><h3>Routes &amp; intents</h3></div>
        <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {[
            { i: 'Book appointment', a: 'Calendar · round-robin', s: 'live' },
            { i: 'Service question', a: 'KB · answer + log', s: 'live' },
            { i: 'Pricing', a: 'Quote sheet · email PDF', s: 'live' },
            { i: 'Complaint', a: 'Escalate to owner', s: 'live' },
            { i: 'Lost lead recovery', a: 'SMS follow-up · D+1', s: 'draft' },
          ].map((r, i) => (
            <div key={i} className="row" style={{ padding: '10px 12px', background: 'rgba(0,0,0,0.2)', border: '1px solid var(--border)', borderRadius: 'var(--radius)', justifyContent: 'space-between' }}>
              <div>
                <div style={{ fontSize: 12 }}>{r.i}</div>
                <div className="mono dim" style={{ fontSize: 10 }}>{r.a}</div>
              </div>
              <StatusTag status={r.s}/>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
function WebsiteTab({ business: b }) {
  return (
    <div style={{ padding: 24 }}>
      <div className="panel">
        <div className="panel-hd">
          <h3>{b.web} · landing page</h3>
          <span className="tag violet">PREVIEW</span>
        </div>
        <div className="panel-body">
          <div style={{
            aspectRatio: '16/9',
            borderRadius: 'var(--radius-lg)',
            background: 'linear-gradient(135deg, rgba(75, 232, 255, 0.15), rgba(139, 107, 255, 0.2), rgba(255, 122, 217, 0.12))',
            border: '1px solid var(--border)',
            position: 'relative',
            overflow: 'hidden',
            display: 'grid', placeItems: 'center',
          }}>
            <div style={{ textAlign: 'center' }}>
              <Icon.Globe style={{ width: 36, height: 36, color: 'var(--violet)', marginBottom: 14 }}/>
              <div className="serif" style={{ fontSize: 28, fontStyle: 'italic', color: '#fff', textShadow: '0 2px 12px rgba(0,0,0,0.4)' }}>Page preview generates here</div>
              <div className="dim" style={{ fontSize: 12, marginTop: 6, color: 'rgba(255,255,255,0.7)' }}>Activate Website Builder to deploy a branded landing page in 30 seconds</div>
            </div>
          </div>
          <button className="btn primary" style={{ marginTop: 14 }}><Icon.Sparkles className="icon"/>Generate landing page</button>
        </div>
      </div>
    </div>
  );
}
function ProposalTab({ business: b }) {
  return (
    <div style={{ padding: 24, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
      <div className="panel">
        <div className="panel-hd"><h3>Proposal builder</h3></div>
        <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div>
            <div className="mono faint" style={{ fontSize: 10, letterSpacing: '0.12em', marginBottom: 6 }}>RECIPIENT</div>
            <input style={inputStyleB} defaultValue={b.ownerEmail || 'owner@' + b.web}/>
          </div>
          <div>
            <div className="mono faint" style={{ fontSize: 10, letterSpacing: '0.12em', marginBottom: 6 }}>PRODUCTS INCLUDED</div>
            <div className="row" style={{ flexWrap: 'wrap', gap: 6 }}>
              <span className="tag live">AI Receptionist · £390/mo</span>
              <span className="tag">+ Website Builder · £0</span>
            </div>
          </div>
          <div>
            <div className="mono faint" style={{ fontSize: 10, letterSpacing: '0.12em', marginBottom: 6 }}>SETUP FEE</div>
            <input style={inputStyleB} defaultValue="£250 one-off"/>
          </div>
          <div>
            <div className="mono faint" style={{ fontSize: 10, letterSpacing: '0.12em', marginBottom: 6 }}>CONTRACT LENGTH</div>
            <select style={inputStyleB}>
              <option>Monthly rolling</option>
              <option>6 months · 10% discount</option>
              <option>12 months · 18% discount</option>
            </select>
          </div>
          <button className="btn primary" style={{ alignSelf: 'flex-start' }}><Icon.Mail className="icon"/>Send proposal</button>
        </div>
      </div>
      <div className="panel">
        <div className="panel-hd">
          <h3>Preview</h3>
          <span className="mono faint" style={{ fontSize: 10 }}>RECIPIENT WILL SEE</span>
        </div>
        <div className="panel-body">
          <div style={{
            padding: 24,
            background: 'rgba(0, 0, 0, 0.25)',
            border: '1px solid var(--border)',
            borderRadius: 'var(--radius)',
            display: 'flex', flexDirection: 'column', gap: 14,
          }}>
            <div className="serif" style={{ fontSize: 22, fontStyle: 'italic' }}>Proposal for {b.name}</div>
            <div className="dim" style={{ fontSize: 12 }}>Prepared by Reza · Demiurge Systems · 22 May 2026</div>
            <div className="divider"/>
            <div style={{ fontSize: 12, lineHeight: 1.6 }}>
              We'll deploy your AI receptionist to handle inbound calls 24/7. Bookings, FAQs, and message-taking — all in your brand voice.
            </div>
            <div className="row" style={{ justifyContent: 'space-between' }}>
              <span className="mono dim" style={{ fontSize: 11 }}>MONTHLY</span>
              <span className="serif" style={{ fontSize: 24, fontStyle: 'italic' }}>£390/mo</span>
            </div>
            <button className="btn primary sm" style={{ alignSelf: 'flex-start' }}>Accept &amp; pay setup fee</button>
          </div>
        </div>
      </div>
    </div>
  );
}

const inputStyleB = {
  padding: '8px 12px',
  background: 'rgba(0, 0, 0, 0.25)',
  border: '1px solid var(--border)',
  borderRadius: 'var(--radius)',
  fontSize: 12,
  width: '100%',
  color: 'var(--text)',
  fontFamily: 'var(--font-mono)',
};

window.Businesses = Businesses;
