/* ============================================================
   Brite Bird Coach — App shell + routing
   ============================================================ */

const TabBar = ({ active, onChange }) => {
  const tabs = [
    { key: 'today', icon: 'sun', label: 'Today' },
    { key: 'leads', icon: 'inbox', label: 'Inbox' },
    { key: 'chat',  icon: 'message-circle', label: 'Chat' },
    { key: 'lock',  icon: 'bell', label: 'Push' },
  ];
  return (
    <div style={{
      background: 'rgba(255,255,255,0.96)',
      backdropFilter: 'blur(14px)',
      borderTop: '1px solid var(--bb-ink-10)',
      padding: '8px 8px calc(20px + env(safe-area-inset-bottom))',
      display: 'grid', gridTemplateColumns: `repeat(${tabs.length}, 1fr)`, gap: 4,
      flex: 'none',
    }}>
      {tabs.map(t => (
        <button key={t.key} onClick={() => onChange(t.key)} style={{
          border: 0, background: 'transparent', padding: '8px 4px',
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
          color: active === t.key ? 'var(--bb-pink)' : 'var(--bb-ink-60)',
          cursor: 'pointer', fontFamily: 'var(--font-family-base)',
        }}>
          <Icon name={t.icon} size={22} stroke={2.2} color="currentColor" />
          <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.06em' }}>{t.label}</span>
        </button>
      ))}
    </div>
  );
};

/* Inbox — full lead list, grouped by status */
const bucketize = (lead) => {
  if (lead.state === 'won' || lead.state === 'lost' || lead.state === 'superseded') return 'closed';
  if (lead.state === 'cold' || lead.days >= 7) return 'cold';
  if (lead.score >= 80) return 'hot';
  return 'active';
};

const BUCKET_META = {
  hot:    { label: 'Hot',    icon: 'flame',         color: 'var(--bb-orange)' },
  active: { label: 'Active', icon: 'message-circle', color: 'var(--bb-pink)' },
  cold:   { label: 'Cold',   icon: 'snowflake',     color: 'var(--bb-ink-60)' },
  closed: { label: 'Closed', icon: 'check',         color: 'var(--bb-ink-40)' },
};

const LeadCard = ({ lead, onOpen }) => {
  const stateMeta = STATE_META[lead.state];
  return (
    <div key={lead.id} onClick={() => onOpen(lead.id)} style={{
      background: 'white', borderRadius: 'var(--radius-lg)',
      padding: '14px 16px', marginBottom: 10,
      display: 'flex', alignItems: 'center', gap: 12,
      boxShadow: 'var(--shadow-sm)', cursor: 'pointer',
    }}>
      <Avatar names={lead.names} size={42} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 15, fontWeight: 700, lineHeight: 1.2 }}>{lead.primary}</div>
        <div style={{ fontSize: 12, fontWeight: 100, color: 'var(--bb-ink-60)', marginTop: 2 }}>
          {lead.city} · {money(lead.quote)} · day {lead.days}
        </div>
        {stateMeta && (
          <div style={{ marginTop: 6 }}>
            <Pill color={stateMeta.color} fg="white" size="sm">{stateMeta.label}</Pill>
          </div>
        )}
      </div>
      <ScoreRing score={lead.score} size={40} stroke={4} />
    </div>
  );
};

const LeadsScreen = ({ leads, onOpen }) => {
  const [closedOpen, setClosedOpen] = React.useState(false);
  const buckets = { hot: [], active: [], cold: [], closed: [] };
  leads.forEach(l => buckets[bucketize(l)].push(l));

  const SectionHeader = ({ k, count, collapsible, open, onToggle }) => {
    const meta = BUCKET_META[k];
    return (
      <div onClick={collapsible ? onToggle : undefined} style={{
        display: 'flex', alignItems: 'center', gap: 8,
        padding: '4px 4px 8px',
        cursor: collapsible ? 'pointer' : 'default',
      }}>
        <Icon name={meta.icon} size={14} color={meta.color} stroke={2.4} />
        <span style={{
          fontSize: 11, fontWeight: 700, letterSpacing: '0.14em',
          textTransform: 'uppercase', color: meta.color,
        }}>{meta.label}</span>
        <span style={{
          fontSize: 11, fontWeight: 700, letterSpacing: '0.06em',
          color: 'var(--bb-ink-40)',
        }}>· {count}</span>
        {collapsible && (
          <span style={{ flex: 1, display: 'flex', justifyContent: 'flex-end' }}>
            <Icon name={open ? 'chevron-up' : 'chevron-down'} size={14} color="var(--bb-ink-40)" stroke={2.4} />
          </span>
        )}
      </div>
    );
  };

  return (
    <div style={{ paddingBottom: 20 }}>
      <TopAppBar sub="All leads" title="Inbox" right={<IconButton icon="filter" />} />
      <div style={{ padding: '0 16px' }}>
        {['hot', 'active', 'cold'].map(k => (
          buckets[k].length > 0 && (
            <div key={k} style={{ marginTop: 14 }}>
              <SectionHeader k={k} count={buckets[k].length} />
              {buckets[k].map(l => <LeadCard key={l.id} lead={l} onOpen={onOpen} />)}
            </div>
          )
        ))}

        {/* Closed — collapsed by default */}
        {buckets.closed.length > 0 && (
          <div style={{ marginTop: 14 }}>
            <SectionHeader
              k="closed"
              count={buckets.closed.length}
              collapsible
              open={closedOpen}
              onToggle={() => setClosedOpen(o => !o)}
            />
            {closedOpen && buckets.closed.map(l => <LeadCard key={l.id} lead={l} onOpen={onOpen} />)}
          </div>
        )}
      </div>
    </div>
  );
};

/* Offline indicator — banner pinned at top of viewport */
const OfflineBanner = () => (
  <div style={{
    background: 'var(--bb-plum)', color: 'var(--bb-yellow)',
    padding: '6px 14px',
    fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase',
    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
    flex: 'none',
  }}>
    <Icon name="wifi-off" size={12} stroke={2.4} />
    Offline · drafts will queue
  </div>
);

/* Mini toast — with optional Undo affordance */
const Toast = ({ text, onUndo }) => (
  <div style={{
    position: 'absolute', bottom: 96, left: '50%', transform: 'translateX(-50%)',
    background: 'var(--bb-plum)', color: 'white',
    padding: '8px 8px 8px 16px', borderRadius: 999,
    fontSize: 13, fontWeight: 700, letterSpacing: '0.02em',
    boxShadow: '0 8px 22px rgba(0,0,0,0.25)', zIndex: 300,
    display: 'inline-flex', alignItems: 'center', gap: 10,
    animation: 'toastIn var(--dur-base) var(--ease-spring)',
  }}>
    <Icon name="check-circle" size={16} stroke={2.4} />
    <span>{text}</span>
    {onUndo && (
      <button
        onClick={onUndo}
        style={{
          background: 'var(--bb-yellow)', color: 'var(--bb-plum)',
          border: 0, borderRadius: 999,
          padding: '6px 14px',
          fontFamily: 'var(--font-family-base)',
          fontSize: 13, fontWeight: 700, letterSpacing: '0.04em',
          cursor: 'pointer',
          display: 'inline-flex', alignItems: 'center', gap: 4,
        }}
      >
        <Icon name="rotate-ccw" size={12} stroke={2.6} /> Undo
      </button>
    )}
  </div>
);

function App() {
  const [tab, setTab] = React.useState('today');
  const [openLead, setOpenLead] = React.useState(null);
  const [statusMap, setStatusMap] = React.useState({});
  const [toast, setToast] = React.useState(null);
  // Frameless on phone-sized viewports — strip the iPhone-mockup chrome so it feels native
  const [isPhone, setIsPhone] = React.useState(typeof window !== 'undefined' && window.innerWidth < 500);
  React.useEffect(() => {
    const update = () => setIsPhone(window.innerWidth < 500);
    update();
    window.addEventListener('resize', update);
    return () => window.removeEventListener('resize', update);
  }, []);

  // Offline indicator — reps in trucks lose signal regularly
  const [online, setOnline] = React.useState(typeof navigator !== 'undefined' ? navigator.onLine : true);
  React.useEffect(() => {
    const goOnline = () => setOnline(true);
    const goOffline = () => setOnline(false);
    window.addEventListener('online', goOnline);
    window.addEventListener('offline', goOffline);
    return () => {
      window.removeEventListener('online', goOnline);
      window.removeEventListener('offline', goOffline);
    };
  }, []);

  const toastTimerRef = React.useRef(null);

  const showToast = (text, onUndo) => {
    setToast({ text, onUndo });
    if (toastTimerRef.current) clearTimeout(toastTimerRef.current);
    toastTimerRef.current = setTimeout(() => setToast(null), 5000); // 5s grace
  };

  const undo = (itemId) => {
    setStatusMap(m => {
      const next = { ...m };
      delete next[itemId];
      return next;
    });
    if (toastTimerRef.current) clearTimeout(toastTimerRef.current);
    setToast({ text: 'Reverted.' });
    setTimeout(() => setToast(null), 1500);
  };

  const onApprove = (itemId) => {
    setStatusMap(m => ({ ...m, [itemId]: 'approved' }));
    showToast('Sent.', () => undo(itemId));
  };
  const onSkip = (itemId) => {
    setStatusMap(m => ({ ...m, [itemId]: 'skipped' }));
    showToast('Skipped.', () => undo(itemId));
  };

  const lead = openLead && LEADS.find(l => l.id === openLead);

  const inner = (
    <div style={{
      width: '100%', height: '100%',
      display: 'flex', flexDirection: 'column',
      background: 'var(--bb-cream)',
      position: 'relative', overflow: 'hidden',
      flex: 1, minHeight: 0,
    }}>
      {!online && <OfflineBanner />}
      <div style={{ flex: 1, overflowY: 'auto', position: 'relative' }}>
        {tab === 'today' && (
          <TodayScreen
            leads={LEADS}
            items={TODAY_ITEMS}
            onOpenLead={(id) => setOpenLead(id)}
            statusMap={statusMap}
            onApprove={onApprove}
            onSkip={onSkip}
          />
        )}
        {tab === 'leads' && <LeadsScreen leads={LEADS} onOpen={(id) => setOpenLead(id)} />}
        {tab === 'chat'  && <ChatScreen />}
        {tab === 'lock'  && (
          <NotificationsScreen
            onOpenLead={(id) => { setTab('today'); setOpenLead(id); }}
            onGoToday={() => setTab('today')}
          />
        )}
      </div>

      <TabBar active={tab} onChange={setTab} />

      {lead && (
        <LeadDeepDive
          lead={lead}
          onClose={() => setOpenLead(null)}
          onApprove={(id) => {
            // approve any matching today item
            const item = TODAY_ITEMS.find(i => i.leadId === id);
            if (item) onApprove(item.id);
            setOpenLead(null);
          }}
        />
      )}

      {toast && <Toast text={toast.text} onUndo={toast.onUndo} />}

      <style>{`
        @keyframes toastIn {
          from { transform: translate(-50%, 20px); opacity: 0; }
          to { transform: translate(-50%, 0); opacity: 1; }
        }
        ::-webkit-scrollbar { display: none; }
      `}</style>
    </div>
  );

  // Phone-sized viewport: drop the mockup frame, fill the screen edge-to-edge like a real PWA
  if (isPhone) {
    return (
      <div style={{
        width: '100vw',
        minHeight: '100vh',
        height: '100vh',
        background: 'var(--bb-cream)',
        fontFamily: 'var(--font-family-base)',
        display: 'flex', flexDirection: 'column',
        overflow: 'hidden',
      }}>
        {inner}
      </div>
    );
  }

  // Desktop / tablet: keep the iPhone-mockup chrome for stakeholder demos
  return (
    <div style={{
      minHeight: '100vh',
      background: 'var(--bb-ink-05)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: '20px 0',
    }}>
      <div style={{
        width: 402, height: 874,
        borderRadius: 48, overflow: 'hidden',
        position: 'relative',
        background: '#000',
        boxShadow: '0 40px 80px rgba(52,14,48,0.28), 0 0 0 12px #181018, 0 0 0 13px rgba(255,255,255,0.04)',
        fontFamily: 'var(--font-family-base)',
      }}>
        {/* dynamic island */}
        <div style={{
          position: 'absolute', top: 11, left: '50%', transform: 'translateX(-50%)',
          width: 126, height: 37, borderRadius: 24, background: '#000', zIndex: 500,
        }} />
        {/* status bar */}
        <div style={{
          position: 'absolute', top: 0, left: 0, right: 0, zIndex: 400,
          padding: '18px 30px 0', display: 'flex', justifyContent: 'space-between',
          alignItems: 'center', height: 54, pointerEvents: 'none',
          color: tab === 'lock' ? 'white' : 'var(--bb-plum)',
          fontWeight: 700, fontSize: 16, letterSpacing: '-0.01em',
        }}>
          <span>9:41</span>
          <span style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
            <Icon name="signal" size={16} stroke={2.4} />
            <Icon name="wifi" size={16} stroke={2.4} />
            <Icon name="battery-full" size={20} stroke={2.4} />
          </span>
        </div>
        {/* content fills rest */}
        <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column' }}>
          {inner}
        </div>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
