// Simple Pro Mobile — Shared primitives
// Tab bar, headers, badges, cells, bottom sheets, quick action tiles
const { useState, useEffect, useRef } = React;

// ── SCREEN LABELS — for back-button "back to X" hints ─────────
const SCREEN_LABELS = {
  home:'Home', jobs:'Jobs', schedule:'Schedule', belle:'Belle', more:'More',
  messages:'Messages', invoices:'Invoices', estimates:'Estimates', reports:'Reports',
  dispatch:'Dispatch', calls:'Calls', 'follow-ups':'Follow-ups',
  customers:'Customers', 'customer-detail':'Customer', 'job-detail':'Job', 'new-job':'New Job',
  'invoice-detail':'Invoice', 'estimate-detail':'Estimate', notifications:'Notifications',
  team:'Team', payment:'Payment', payments:'Payments',
  settings:'Settings', 'settings-profile':'Profile', 'settings-security':'Security',
  'settings-notifications':'Notifications', 'settings-company':'Company',
  'settings-payments':'Payments', 'settings-billing':'Billing', 'settings-pricebook':'Price Book',
  'settings-belle':'Belle AI', 'settings-templates':'Templates', 'settings-integrations':'Integrations',
  'settings-data':'Data', 'settings-privacy':'Privacy', 'settings-help':'Help',
  'settings-contact':'Contact', 'settings-about':'About', 'settings-team':'Team',
  'team-member':'Member',
  campaigns:'Campaigns', 'campaign-detail':'Campaign', plans:'Plans', 'billing-pdf':'Statement',
};
function screenLabel(key) { return SCREEN_LABELS[key] || 'Back'; }

// ── NAV CONTEXT — provides goBack + backLabel to every screen ─
const NavContext = React.createContext({ goBack: null, backLabel: 'Back' });
function useNav() { return React.useContext(NavContext); }

// ── ICONS ─────────────────────────────────────────────────────
const Icons = {
  home:     <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9.5L12 3l9 6.5V20a1 1 0 01-1 1H4a1 1 0 01-1-1V9.5z"/><path d="M9 21V12h6v9"/></svg>,
  jobs:     <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 7V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v2"/><line x1="12" y1="12" x2="12" y2="16"/><line x1="10" y1="14" x2="14" y2="14"/></svg>,
  schedule: <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/><line x1="8" y1="14" x2="8" y2="14"/><line x1="12" y1="14" x2="12" y2="14"/><line x1="16" y1="14" x2="16" y2="14"/></svg>,
  invoices: <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><line x1="10" y1="9" x2="8" y2="9"/></svg>,
  more:     <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><circle cx="5" cy="12" r="1.5" fill="currentColor" stroke="none"/><circle cx="12" cy="12" r="1.5" fill="currentColor" stroke="none"/><circle cx="19" cy="12" r="1.5" fill="currentColor" stroke="none"/></svg>,
  belle:    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2C6.477 2 2 6.477 2 12s4.477 10 10 10 10-4.477 10-10S17.523 2 12 2z"/><path d="M8 12s1.5 2 4 2 4-2 4-2"/><line x1="9" y1="9" x2="9.01" y2="9"/><line x1="15" y1="9" x2="15.01" y2="9"/></svg>,
  back:     <svg width="10" height="17" viewBox="0 0 10 17" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M8.5 1.5L1.5 8.5l7 7"/></svg>,
  plus:     <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="8" y1="2" x2="8" y2="14"/><line x1="2" y1="8" x2="14" y2="8"/></svg>,
  phone:    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.5 19.5 0 013.7 10.74 19.79 19.79 0 01.67 2.18 2 2 0 012.65 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.91 7.6a16 16 0 006.29 6.29l.97-1.97a2 2 0 012.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0122 16.92z"/></svg>,
  message:  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/></svg>,
  map:      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><polygon points="3 6 9 3 15 6 21 3 21 18 15 21 9 18 3 21"/><line x1="9" y1="3" x2="9" y2="18"/><line x1="15" y1="6" x2="15" y2="21"/></svg>,
  camera:   <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><path d="M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h4l2-3h6l2 3h4a2 2 0 012 2z"/><circle cx="12" cy="13" r="4"/></svg>,
  note:     <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>,
  dollar:   <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6"/></svg>,
  check:    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>,
  clock:    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>,
  user:     <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>,
  warning:  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>,
  send:     <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>,
  chevronR: <svg width="7" height="12" viewBox="0 0 7 12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M1 1l5 5-5 5"/></svg>,
  pin:      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0118 0z"/><circle cx="12" cy="10" r="3"/></svg>,
  wifi:     <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M1.42 9A16 16 0 0122.58 9"/><path d="M5.5 12.7A10 10 0 0118.5 12.7"/><path d="M10 16.5a4 4 0 014 0"/><line x1="12" y1="20" x2="12.01" y2="20" strokeWidth="3"/></svg>,
  team:     <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 00-3-3.87"/><path d="M16 3.13a4 4 0 010 7.75"/></svg>,
  sparkle:  <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l2.4 7.2H22l-6.3 4.6 2.4 7.2L12 17l-6.1 4 2.4-7.2L2 9.2h7.6L12 2z"/></svg>,
};

// ── STATUS BADGE ──────────────────────────────────────────────
function Badge({ status, small }) {
  const map = {
    'paid':        { bg:'#e6f7ef', color:'#0f6b3c', dot:'#1a9e5c', label:'Paid' },
    'completed':   { bg:'#e6f7ef', color:'#0f6b3c', dot:'#1a9e5c', label:'Completed' },
    'overdue':     { bg:'#fef3e2', color:'#92520a', dot:'#d97706', label:'Overdue' },
    'attention':   { bg:'#fef3e2', color:'#92520a', dot:'#d97706', label:'Attention' },
    'canceled':    { bg:'#fef2f2', color:'#991b1b', dot:'#dc2626', label:'Canceled' },
    'past due':    { bg:'#fef2f2', color:'#991b1b', dot:'#dc2626', label:'Past due' },
    'scheduled':   { bg:'#eff6ff', color:'#1e40af', dot:'#2563eb', label:'Scheduled' },
    'in progress': { bg:'#eff6ff', color:'#1e40af', dot:'#2563eb', label:'In Progress' },
    'on my way':   { bg:'#f0fdf4', color:'#166534', dot:'#16a34a', label:'On My Way' },
    'arrived':     { bg:'#f0fdf4', color:'#166534', dot:'#16a34a', label:'Arrived' },
    'draft':       { bg:'#f3f4f6', color:'#374151', dot:'#6b7280', label:'Draft' },
    'unpaid':      { bg:'#fef3e2', color:'#92520a', dot:'#d97706', label:'Unpaid' },
    'approved':    { bg:'#e6f7ef', color:'#0f6b3c', dot:'#1a9e5c', label:'Approved' },
    'urgent':      { bg:'#fef2f2', color:'#991b1b', dot:'#dc2626', label:'Urgent' },
  };
  const s = map[status] || map.draft;
  const sz = small ? 10 : 11;
  return (
    <div style={{display:'inline-flex',alignItems:'center',gap:4,background:s.bg,color:s.color,
      fontSize:sz,fontWeight:600,padding: small ? '2px 7px':'3px 8px',borderRadius:999,whiteSpace:'nowrap'}}>
      <div style={{width:small?5:6,height:small?5:6,borderRadius:'50%',background:s.dot,flexShrink:0}}/>
      {s.label}
    </div>
  );
}

// ── BOTTOM TAB BAR ────────────────────────────────────────────
function TabBar({ active, onTab }) {
  const tabs = [
    { id:'home',     label:'Home',     icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9.5L12 3l9 6.5V20a1 1 0 01-1 1H4a1 1 0 01-1-1V9.5z"/><path d="M9 21V12h6v9"/></svg> },
    { id:'jobs',     label:'Jobs',     icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 7V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v2"/></svg> },
    { id:'belle',    label:'Belle',    icon: null },
    { id:'schedule', label:'Schedule', icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg> },
    { id:'more',     label:'Menu',     icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg> },
  ];
  return (
    <div style={{
      position:'absolute', bottom:0, left:0, right:0, zIndex:100,
      height:83,
      background:'rgba(248,248,250,0.97)',
      backdropFilter:'saturate(200%) blur(32px)',
      WebkitBackdropFilter:'saturate(200%) blur(32px)',
      borderTop:'0.5px solid rgba(0,0,0,0.08)',
      display:'flex', alignItems:'flex-start', paddingTop:10,
    }}>
      {tabs.map(t => {
        if (t.id === 'belle') {
          const isActive = active === 'belle';
          return (
            <div key="belle" onClick={() => onTab('belle')}
              style={{flex:1,display:'flex',flexDirection:'column',
                alignItems:'center',cursor:'pointer',gap:0,paddingTop:2}}>
              <div style={{
                width:40, height:40, borderRadius:'50%',
                background: isActive ? '#0062c4' : '#0071e3',
                display:'flex',alignItems:'center',justifyContent:'center',
                boxShadow:'0 2px 10px rgba(0,113,227,0.38)',
              }}>
                {/* Bell icon — matching real app */}
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9"/>
                  <path d="M13.73 21a2 2 0 01-3.46 0"/>
                </svg>
              </div>
              <span style={{
                fontSize:10, lineHeight:1, marginTop:3,
                fontWeight: isActive ? 600 : 500,
                color: isActive ? '#0071e3' : 'rgba(0,113,227,0.75)',
                letterSpacing:'0.01em',
              }}>Belle</span>
            </div>
          );
        }
        const isActive = active === t.id;
        return (
          <div key={t.id} onClick={() => onTab(t.id)}
            style={{flex:1, display:'flex', flexDirection:'column', alignItems:'center',
              gap:3, cursor:'pointer', paddingTop:2,
              color: isActive ? '#0071e3' : 'rgba(0,0,0,0.26)',
              transition:'color 0.1s'}}>
            <div style={{width:24,height:24,display:'flex',alignItems:'center',justifyContent:'center'}}>
              {React.cloneElement(t.icon, {
                width:22, height:22,
                strokeWidth: isActive ? 2.05 : 1.6,
              })}
            </div>
            <span style={{
              fontSize:10, lineHeight:1,
              fontWeight: isActive ? 600 : 400,
              letterSpacing:'0.01em',
            }}>{t.label}</span>
          </div>
        );
      })}
    </div>
  );
}

// ── TOP NAV HEADER ────────────────────────────────────────────
function NavHeader({ title, subtitle, backLabel, onBack, action, transparent }) {
  const nav = useNav();
  // Special sentinel: onBack="__back" means "use context goBack, hide if unavailable"
  let effectiveOnBack;
  if (onBack === '__back') {
    effectiveOnBack = nav.goBack;  // null when stack is empty → back button hides
  } else if (onBack !== undefined) {
    effectiveOnBack = onBack;
  } else {
    effectiveOnBack = nav.goBack;
  }
  const effectiveLabel = backLabel !== undefined ? backLabel : nav.backLabel;
  const showBack = !!effectiveOnBack;
  return (
    <div style={{
      paddingTop: showBack ? 54 : 56,
      paddingBottom: showBack ? 12 : 18,
      paddingLeft: 20,
      paddingRight: 16,
      display:'flex',
      alignItems: showBack ? 'center' : 'flex-end',
      justifyContent:'space-between',
      background: transparent ? 'transparent' : '#0f172a',
      borderBottom: 'none',
      position:'sticky',top:0,zIndex:40,
    }}>
      {showBack ? (
        <div style={{display:'flex',alignItems:'center',gap:0,flex:1,minWidth:0}}>
          <div onClick={effectiveOnBack}
            style={{display:'flex',alignItems:'center',gap:5,color:'rgba(255,255,255,0.55)',cursor:'pointer',marginRight:12,
              fontSize:16,fontWeight:400,padding:'4px 0',flexShrink:0}}>
            <span style={{display:'flex',alignItems:'center',color:'rgba(255,255,255,0.55)'}}>{Icons.back}</span>
            {effectiveLabel && <span style={{marginLeft:2,maxWidth:110,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{effectiveLabel}</span>}
          </div>
          <div style={{fontSize:17,fontWeight:600,color:'white',letterSpacing:'-0.012em',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{title}</div>
        </div>
      ) : (
        <div style={{flex:1}}>
          {subtitle && <div style={{fontSize:13,fontWeight:500,color:'rgba(255,255,255,0.38)',marginBottom:2}}>{subtitle}</div>}
          <div style={{fontSize:30,fontWeight:700,color:'white',letterSpacing:'-0.025em',lineHeight:1.15}}>{title}</div>
        </div>
      )}
      {action && <div style={{flexShrink:0}}>{action}</div>}
    </div>
  );
}

// ── SECTION HEADER ────────────────────────────────────────────
function SectionHeader({ title, action, onAction }) {
  return (
    <div style={{padding:'16px 20px 8px',display:'flex',justifyContent:'space-between',alignItems:'center'}}>
      <span style={{fontSize:17,fontWeight:600,color:'#111',letterSpacing:'-0.012em'}}>{title}</span>
      {action && <span onClick={onAction} style={{fontSize:14,color:'#0071e3',cursor:'pointer',fontWeight:400}}>{action}</span>}
    </div>
  );
}

// ── CARD CONTAINER ────────────────────────────────────────────
function Card({ children, style, onClick, mx = 16 }) {
  const [pressed, setPressed] = useState(false);
  return (
    <div
      onClick={onClick}
      onMouseDown={onClick ? () => setPressed(true) : undefined}
      onMouseUp={onClick ? () => setPressed(false) : undefined}
      onMouseLeave={onClick ? () => setPressed(false) : undefined}
      style={{
        margin: `0 ${mx}px`,
        background: pressed ? '#f7f7f8' : 'white',
        borderRadius:14,
        border:'1px solid rgba(0,0,0,0.07)',
        overflow:'hidden',
        cursor: onClick ? 'pointer' : undefined,
        transition:'background 0.1s',
        ...style,
      }}>
      {children}
    </div>
  );
}

// ── LIST CELL ─────────────────────────────────────────────────
function ListCell({ icon, iconBg, title, subtitle, right, badge, onTap, isLast, chevron=true }) {
  const [pressed, setPressed] = useState(false);
  return (
    <div
      onClick={onTap}
      onMouseDown={onTap ? () => setPressed(true) : undefined}
      onMouseUp={onTap ? () => setPressed(false) : undefined}
      onMouseLeave={onTap ? () => setPressed(false) : undefined}
      style={{
        padding:'13px 16px',
        display:'flex',alignItems:'center',gap:12,
        background: pressed ? '#f2f2f4' : 'white',
        borderBottom: isLast ? 'none' : '0.5px solid rgba(0,0,0,0.07)',
        cursor: onTap ? 'pointer' : 'default',
        transition:'background 0.1s',
      }}>
      {icon && (
        <div style={{width:38,height:38,borderRadius:10,background:iconBg||'#e8f2fd',
          display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0,color:'#0071e3'}}>
          {icon}
        </div>
      )}
      <div style={{flex:1,minWidth:0}}>
        <div style={{fontSize:15,fontWeight:500,color:'#111',letterSpacing:'-0.008em',lineHeight:1.3,
          whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{title}</div>
        {subtitle && <div style={{fontSize:13,color:'rgba(0,0,0,0.45)',marginTop:2,letterSpacing:'-0.005em',
          whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{subtitle}</div>}
      </div>
      {badge && <div style={{flexShrink:0}}>{badge}</div>}
      {right && <div style={{fontSize:13,fontWeight:500,color:'#111',fontVariantNumeric:'tabular-nums',flexShrink:0}}>{right}</div>}
      {chevron && onTap && <div style={{color:'rgba(0,0,0,0.25)',flexShrink:0,marginLeft:4}}>{Icons.chevronR}</div>}
    </div>
  );
}

// ── BIG ACTION BUTTON ─────────────────────────────────────────
function PrimaryButton({ label, icon, onTap, color='#0071e3', textColor='white', style }) {
  const [pressed, setPressed] = useState(false);
  return (
    <div onClick={onTap}
      onMouseDown={() => setPressed(true)} onMouseUp={() => setPressed(false)} onMouseLeave={() => setPressed(false)}
      style={{
        height:52, borderRadius:13, background: pressed ? '#0062c4' : color,
        display:'flex',alignItems:'center',justifyContent:'center',gap:8,
        color:textColor, fontSize:16, fontWeight:600, cursor:'pointer',
        letterSpacing:'-0.012em', transition:'all 0.1s',
        transform: pressed ? 'scale(0.98)' : 'scale(1)',
        ...style,
      }}>
      {icon && <span style={{display:'flex',alignItems:'center'}}>{icon}</span>}
      {label}
    </div>
  );
}

function SecondaryButton({ label, icon, onTap, style }) {
  const [pressed, setPressed] = useState(false);
  return (
    <div onClick={onTap}
      onMouseDown={() => setPressed(true)} onMouseUp={() => setPressed(false)} onMouseLeave={() => setPressed(false)}
      style={{
        height:48, borderRadius:12, background: pressed ? '#eaeaec' : '#f2f2f4',
        display:'flex',alignItems:'center',justifyContent:'center',gap:7,
        color:'#111', fontSize:15, fontWeight:500, cursor:'pointer',
        letterSpacing:'-0.008em', transition:'background 0.1s',
        ...style,
      }}>
      {icon && <span style={{display:'flex',alignItems:'center',color:'rgba(0,0,0,0.5)'}}>{icon}</span>}
      {label}
    </div>
  );
}

// ── QUICK ACTION TILE ─────────────────────────────────────────
function QuickTile({ icon, label, color, bg, onTap }) {
  const [pressed, setPressed] = useState(false);
  return (
    <div onClick={onTap}
      onMouseDown={() => setPressed(true)} onMouseUp={() => setPressed(false)} onMouseLeave={() => setPressed(false)}
      style={{
        flex:1, display:'flex', flexDirection:'column', alignItems:'center',
        gap:6, padding:'12px 4px', background: pressed ? '#eaeaec' : bg||'#f2f2f4',
        borderRadius:12, cursor:'pointer', transition:'background 0.1s',
      }}>
      <div style={{width:40,height:40,borderRadius:11,background:color||'#0071e3',
        display:'flex',alignItems:'center',justifyContent:'center',color:'white'}}>
        {icon}
      </div>
      <span style={{fontSize:11,fontWeight:500,color:'#111',letterSpacing:'-0.005em',textAlign:'center',lineHeight:1.3}}>{label}</span>
    </div>
  );
}

// ── BOTTOM SHEET ──────────────────────────────────────────────
function BottomSheet({ open, onClose, title, children, halfHeight }) {
  return (
    <>
      {open && (
        <div onClick={onClose}
          style={{position:'absolute',inset:0,background:'rgba(0,0,0,0.4)',zIndex:200,transition:'opacity 0.2s'}}/>
      )}
      <div style={{
        position:'absolute', bottom:0, left:0, right:0, zIndex:201,
        background:'white', borderRadius:'20px 20px 0 0',
        transform: open ? 'translateY(0)' : 'translateY(100%)',
        transition:'transform 0.3s cubic-bezier(0.32,0.72,0,1)',
        maxHeight: halfHeight ? '55%' : '85%',
        display:'flex', flexDirection:'column',
        boxShadow:'0 -4px 32px rgba(0,0,0,0.12)',
      }}>
        <div style={{display:'flex',justifyContent:'center',paddingTop:8,paddingBottom:6,flexShrink:0}}>
          <div style={{width:36,height:4,borderRadius:2,background:'rgba(0,0,0,0.15)'}}/>
        </div>
        {title && (
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',
            padding:'4px 20px 12px',borderBottom:'0.5px solid rgba(0,0,0,0.08)',flexShrink:0}}>
            <span style={{fontSize:16,fontWeight:600,color:'#111'}}>{title}</span>
            <div onClick={onClose} style={{fontSize:14,color:'#0071e3',cursor:'pointer',fontWeight:400}}>Done</div>
          </div>
        )}
        <div style={{overflowY:'auto',flex:1}}>
          {children}
        </div>
      </div>
    </>
  );
}

// ── BELLE SUGGESTION CARD ─────────────────────────────────────
function BelleSuggestion({ text, actions, onAction }) {
  return (
    <div style={{margin:'10px 16px',background:'#f5f0ff',border:'1px solid rgba(124,58,237,0.14)',
      borderRadius:14,padding:'12px 14px'}}>
      <div style={{display:'flex',alignItems:'center',gap:6,marginBottom:7}}>
        <div style={{width:18,height:18,borderRadius:'50%',background:'linear-gradient(135deg,#7c3aed,#4f46e5)',
          display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
          <svg width="9" height="9" viewBox="0 0 24 24" fill="white"><path d="M12 2l2.09 6.26L20 9.27l-4.91 4.73 1.18 6.88L12 17.77l-6.27 3.11 1.18-6.88L2 9.27l5.91-1.01L12 2z"/></svg>
        </div>
        <span style={{fontSize:11,fontWeight:700,color:'#7c3aed',letterSpacing:'0.04em',textTransform:'uppercase'}}>Belle</span>
      </div>
      <div style={{fontSize:14,color:'#111',lineHeight:1.55,letterSpacing:'-0.005em'}}>{text}</div>
      {actions && actions.length > 0 && (
        <div style={{display:'flex',gap:8,marginTop:10}}>
          {actions.map((a,i) => (
            <button key={i} onClick={() => onAction && onAction(a)}
              style={{flex: i===0 ? 1.5 : 1, height:34, borderRadius:8,
                background: i===0 ? '#7c3aed' : 'rgba(124,58,237,0.1)',
                color: i===0 ? 'white' : '#4c1d95',
                border:'none',fontSize:13,fontWeight: i===0 ? 600:400,cursor:'pointer'}}>
              {a}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// ── STAT CARD ─────────────────────────────────────────────────
function StatCard({ label, value, color, bg, sub, onTap }) {
  const [pressed, setPressed] = useState(false);
  return (
    <div onClick={onTap}
      onMouseDown={onTap?()=>setPressed(true):undefined} onMouseUp={onTap?()=>setPressed(false):undefined} onMouseLeave={onTap?()=>setPressed(false):undefined}
      style={{background:pressed?'#eaeaec':bg||'#e8f2fd',borderRadius:14,padding:'14px 16px',cursor:onTap?'pointer':'default',transition:'background 0.1s'}}>
      <div style={{fontSize:28,fontWeight:700,color:color||'#0071e3',lineHeight:1.1,fontVariantNumeric:'tabular-nums',letterSpacing:'-0.02em'}}>{value}</div>
      <div style={{fontSize:13,fontWeight:500,color:'rgba(0,0,0,0.55)',marginTop:3}}>{label}</div>
      {sub && <div style={{fontSize:11,color:'rgba(0,0,0,0.35)',marginTop:2}}>{sub}</div>}
    </div>
  );
}

// ── AVATAR ────────────────────────────────────────────────────
function Avatar({ name, size=36, color='#e8f2fd', textColor='#0071e3' }) {
  const initials = name.split(' ').map(w=>w[0]).slice(0,2).join('');
  return (
    <div style={{width:size,height:size,borderRadius:'50%',background:color,
      display:'flex',alignItems:'center',justifyContent:'center',
      fontSize:size*0.36,fontWeight:600,color:textColor,flexShrink:0,letterSpacing:'-0.01em'}}>
      {initials}
    </div>
  );
}

// ── OFFLINE BANNER ─────────────────────────────────────────────
function OfflineBanner() {
  return (
    <div style={{margin:'8px 16px',background:'#1a1a1c',borderRadius:10,padding:'10px 14px',
      display:'flex',alignItems:'center',gap:8}}>
      <div style={{color:'#d97706',display:'flex',alignItems:'center'}}>{Icons.wifi}</div>
      <div>
        <div style={{fontSize:13,fontWeight:600,color:'white'}}>Offline mode</div>
        <div style={{fontSize:12,color:'rgba(255,255,255,0.5)'}}>Changes saved locally. Syncing when connection returns.</div>
      </div>
    </div>
  );
}

// ── MENU OVERLAY (slide-up sheet) ─────────────────────────────
function MenuOverlay({ open, onClose, onNav, role }) {
  const sections = [
    {
      title: 'CORE',
      items: [
        { icon: Icons.home,     label:'Home',         screen:'home' },
        { icon: Icons.user,     label:'Customers',    screen:'customers' },
        { icon: Icons.jobs,     label:'Jobs',         screen:'jobs' },
        { icon: Icons.schedule, label:'Schedule',     screen:'schedule' },
      ]
    },
    {
      title: 'COMMUNICATION',
      items: [
        { icon: Icons.phone,    label:'Calls',        screen:'calls' },
        { icon: Icons.message,  label:'Texts',        screen:'messages' },
        { icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>, label:'Diagnose', screen:'belle' },
        { icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>, label:'Follow Ups', screen:'follow-ups' },
        { icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><path d="M22 2L11 13M22 2L15 22l-4-9-9-4 20-7z"/></svg>, label:'Campaigns', screen:'campaigns' },
      ]
    },
    {
      title: 'FINANCE',
      items: [
        { icon: Icons.dollar,   label:'Estimates',    screen:'estimates' },
        { icon: Icons.invoices, label:'Invoices',     screen:'invoices' },
        { icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><rect x="1" y="4" width="22" height="16" rx="2"/><line x1="1" y1="10" x2="23" y2="10"/></svg>, label:'Payments', screen:'payments' },
      ]
    },
    {
      title: 'MORE',
      items: [
        { icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg>, label:'Reports', screen:'reports' },
        { icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><circle cx="12" cy="12" r="3"/><path d="M19.07 4.93l-1.41 1.41M5.93 5.93l-1.41-1.41M4 12H2M22 12h-2M19.07 19.07l-1.41-1.41M5.93 18.07l-1.41 1.41M12 22v-2M12 4V2"/></svg>, label:'Settings', screen:'settings' },
        { icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><path d="M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0118 0z"/><circle cx="12" cy="10" r="3"/></svg>, label:'Dispatch', screen:'dispatch' },
        { icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6"/></svg>, label:'Billing', screen:'settings-billing' },
      ]
    },
  ];

  function handleNav(screen) {
    onClose();
    onNav(screen, { __fromMenu: true });
  }

  return (
    <>
      {open && (
        <div onClick={onClose}
          style={{position:'absolute',inset:0,background:'rgba(0,0,0,0.4)',zIndex:200}}/>
      )}
      <div style={{
        position:'absolute', bottom:0, right:0, zIndex:201,
        width:'67%',
        height:'67%',
        background:'#f2f2f7',
        borderRadius:'16px 16px 0 0',
        transform: open ? 'translateY(0)' : 'translateY(100%)',
        transition:'transform 0.32s cubic-bezier(0.32,0.72,0,1)',
        display:'flex', flexDirection:'column',
        boxShadow:'-4px -4px 32px rgba(0,0,0,0.18)',
        overflow:'hidden',
      }}>
        {/* Handle */}
        <div style={{display:'flex',justifyContent:'center',padding:'10px 0 6px',flexShrink:0}}>
          <div style={{width:32,height:4,borderRadius:2,background:'rgba(0,0,0,0.15)'}}/>
        </div>

        <div style={{overflowY:'auto',flex:1,paddingBottom:90}}>
          {sections.map(sec => (
            <div key={sec.title} style={{marginBottom:6}}>
              <div style={{padding:'8px 14px 4px',fontSize:11,fontWeight:600,
                color:'rgba(0,0,0,0.35)',letterSpacing:'0.05em'}}>
                {sec.title}
              </div>
              <div style={{margin:'0 10px',background:'white',borderRadius:12,
                overflow:'hidden',border:'0.5px solid rgba(0,0,0,0.07)'}}>
                {sec.items.map((item, i) => (
                  <div key={item.label} onClick={() => handleNav(item.screen)}
                    style={{
                      minHeight:50,
                      padding:'0 12px',
                      display:'flex', alignItems:'center', gap:10,
                      borderBottom: i < sec.items.length-1
                        ? '0.5px solid rgba(0,0,0,0.07)' : 'none',
                      cursor:'pointer',
                    }}>
                    <div style={{width:24,height:24,borderRadius:6,
                      background:'#f2f2f7',
                      display:'flex',alignItems:'center',justifyContent:'center',
                      color:'rgba(0,0,0,0.45)',flexShrink:0}}>
                      {React.cloneElement(item.icon, {width:14,height:14,strokeWidth:1.8})}
                    </div>
                    <div style={{flex:1,fontSize:14,fontWeight:400,color:'#111',
                      letterSpacing:'-0.01em',lineHeight:1}}>{item.label}</div>
                    <svg width="6" height="10" viewBox="0 0 7 12" fill="none"
                      stroke="rgba(0,0,0,0.18)" strokeWidth="2" strokeLinecap="round">
                      <path d="M1 1l5 5-5 5"/>
                    </svg>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

Object.assign(window, {
  Icons, Badge, TabBar, NavHeader, SectionHeader, Card, ListCell,
  PrimaryButton, SecondaryButton, QuickTile, BottomSheet,
  BelleSuggestion, StatCard, Avatar, OfflineBanner, MenuOverlay,
  SCREEN_LABELS, screenLabel, NavContext, useNav,
});
