// Dashboard.jsx — overview at-a-glance for Owner.

const Dashboard = ({ onNavigate }) => {
  const items = window.SAMPLE_PREP_ITEMS;
  const progress = window.SAMPLE_PREP_PROGRESS;

  const totalItems = items.filter(i => i.target > 0).length;
  const doneItems = items.filter(i => {
    if (i.target === 0) return false;
    const done = (progress[i.id] || []).reduce((s, p) => s + p.qty, 0);
    return done >= i.target;
  }).length;
  const prepPct = Math.round((doneItems / totalItems) * 100);

  // Live count of broadcasts in the last 24h from Supabase
  const [pendingCount, setPendingCount] = useState(null);
  useEffect(() => {
    if (!window.supa) return;
    let cancelled = false;
    const since = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
    window.supa
      .from('broadcasts')
      .select('id', { count: 'exact', head: true })
      .eq('restaurant_id', window.RESTAURANT_ID)
      .gte('created_at', since)
      .then(({ count, error }) => { if (!cancelled && !error) setPendingCount(count ?? 0); });
    return () => { cancelled = true; };
  }, []);

  const lowStock = window.SAMPLE_INVENTORY.filter(i => i.last < i.par * 0.4);

  const recent = [
    { staff: 'mei',   action: 'logged 2 qt of Basic Sauce',     time: '12:14' },
    { staff: 'jorge', action: 'completed BF Pre-Cut (10 lb)',   time: '11:58' },
    { staff: 'bo',    action: 'started Cabbage (long)',         time: '11:42' },
    { staff: 'tina',  action: 'acknowledged broadcast',         time: '11:30' },
    { staff: 'ana',   action: 'logged 1 tray of Cheese Rangoon',time: '11:40' },
  ];

  return (
    <div className="portal-page-wide" style={{ maxWidth: 1280 }}>
      <div className="portal-page-header">
        <div>
          <h1 className="portal-page-title">Tuesday, April 28</h1>
          <div className="portal-page-subtitle">Here's what's happening at the shop today.</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <PBtn variant="secondary" icon="print" onClick={() => window.print()}>Print prep sheet</PBtn>
          <PBtn variant="primary" icon="plus" onClick={() => onNavigate && onNavigate('broadcasts')}>New broadcast</PBtn>
        </div>
      </div>

      {/* Stats row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 28 }}>
        <div className="portal-stat">
          <div className="portal-stat-label">Prep Completion</div>
          <div className="portal-stat-value">{prepPct}%</div>
          <div className="portal-stat-sub">{doneItems} of {totalItems} items done</div>
        </div>
        <div className="portal-stat">
          <div className="portal-stat-label">On the floor</div>
          <div className="portal-stat-value">5</div>
          <div className="portal-stat-sub">2 line · 2 front · 1 dish</div>
        </div>
        <div className="portal-stat">
          <div className="portal-stat-label">Broadcasts (24h)</div>
          <div className="portal-stat-value">{pendingCount === null ? '—' : pendingCount}</div>
          <div className="portal-stat-sub">sent in the last 24 hours</div>
        </div>
        <div className="portal-stat">
          <div className="portal-stat-label">Low Stock</div>
          <div className="portal-stat-value">{lowStock.length}</div>
          <div className="portal-stat-sub">items below 40% of par</div>
        </div>
      </div>

      {/* Two-column: prep snapshot + activity feed */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 360px', gap: 20 }}>
        <div className="portal-card">
          <div className="portal-card-header">
            <div className="portal-card-title">Prep Progress</div>
            <a href="#" onClick={e => { e.preventDefault(); onNavigate && onNavigate('prep'); }} style={{ fontSize: 12.5, color: 'var(--fg-2)', textDecoration: 'none' }}>Open template →</a>
          </div>
          <div style={{ padding: '4px 0 8px' }}>
            {['Sauce','Vegetable','Meat','Other'].map(cat => {
              const catItems = items.filter(i => i.category === cat && i.target > 0);
              const catDone = catItems.filter(i => (progress[i.id] || []).reduce((s,p) => s + p.qty, 0) >= i.target).length;
              const pct = catItems.length ? Math.round((catDone / catItems.length) * 100) : 0;
              return (
                <div key={cat} style={{
                  padding: '12px 18px', borderBottom: '1px solid var(--border-2)',
                  display: 'grid', gridTemplateColumns: '120px 1fr 80px 80px',
                  gap: 16, alignItems: 'center',
                }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{cat}</div>
                  <div style={{ height: 6, background: 'var(--bg-sunken)', borderRadius: 999, overflow: 'hidden' }}>
                    <div style={{ height: '100%', width: `${pct}%`, background: 'var(--fg-1)', borderRadius: 999, transition: 'width 400ms' }} />
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--fg-2)', textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>
                    {catDone}/{catItems.length}
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--fg-1)', textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontWeight: 500 }}>
                    {pct}%
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        <div className="portal-card">
          <div className="portal-card-header">
            <div className="portal-card-title">Recent Activity</div>
          </div>
          <div style={{ padding: '6px 0' }}>
            {recent.map((r, i) => {
              const s = window.SAMPLE_STAFF.find(x => x.id === r.staff);
              return (
                <div key={i} style={{
                  display: 'flex', gap: 10, alignItems: 'flex-start',
                  padding: '10px 16px',
                }}>
                  <PAvatar staff={s} size={26} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, color: 'var(--fg-1)' }}>
                      <span style={{ fontWeight: 500 }}>{s.name}</span>{' '}
                      <span style={{ color: 'var(--fg-2)' }}>{r.action}</span>
                    </div>
                    <div style={{ fontSize: 11, color: 'var(--fg-3)', marginTop: 2, fontVariantNumeric: 'tabular-nums' }}>{r.time}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
};

window.Dashboard = Dashboard;
