/* ============================================================
   TRELLIS — Dashboard page
   Exports: DashboardPage
   ============================================================ */

function DashStatCard({ s, i, openPage }) {
  const hues = { clients: 330, visits: 96, cards: 248, followups: 35 };
  const targets = { clients: 'clients', visits: 'checkin', cards: 'harvest', followups: 'clients' };
  const hue = hues[s.k] || 310;
  return (
    <button onClick={() => openPage(targets[s.k] || 'dashboard')} className="glass" style={{
      borderRadius: 'var(--radius-l)', padding: '20px 22px', display: 'flex', flexDirection: 'column', gap: 10,
      textAlign: 'left', cursor: 'pointer',
      boxShadow: 'var(--shadow-card)', animation: `trellis-rise .5s var(--ease-spring) ${i * 0.06}s backwards`,
      transition: 'transform .2s var(--ease-spring), box-shadow .2s'
    }}
      onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-3px)'; e.currentTarget.style.boxShadow = 'var(--shadow-pop)'; }}
      onMouseLeave={e => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = 'var(--shadow-card)'; }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
        <span style={{ fontSize: 12.5, fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--ink-faint)' }}>{s.label}</span>
        <span style={{ width: 8, height: 8, borderRadius: 99, background: `oklch(0.68 0.13 ${hue})`, marginTop: 4 }}></span>
      </div>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12 }}>
        <div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 34, letterSpacing: '-0.03em', lineHeight: 1 }}>{s.value}</div>
          <div className="t-faint" style={{ fontSize: 12.5, fontWeight: 600, marginTop: 6 }}>{s.delta}</div>
        </div>
        <Sparkline data={s.spark} hue={hue} />
      </div>
    </button>
  );
}

// Every number on the dashboard derives from the live Firestore data when a
// real user is signed in. Demo DASH shows only in signed-out demo mode.
function buildLiveDash(D) {
  const clients = D.clients || [];
  const visits = D.VISITS || [];
  const now = new Date();
  const monthKey = now.toISOString().slice(0, 7);
  const monthName = now.toLocaleString('en-CA', { month: 'long' });
  const monthVisits = visits.filter(v => (v.ts || '').slice(0, 7) === monthKey).length;
  const picked = (D.HARVEST || []).filter(c => c.col === 'picked').length;
  const cutoff = new Date(Date.now() - 30 * 864e5).toISOString().slice(0, 10);
  const overdue = clients.filter(c => !c.lastVisitDate || c.lastVisitDate < cutoff).length;
  const flat = v => Array(9).fill(v);
  const programs = [
    { name: 'Food', hue: 96 }, { name: 'Settlement', hue: 248 }, { name: 'Domestic Violence', hue: 330 }
  ].map(p => ({ ...p, count: clients.filter(c => c.formCategory === p.name).length }));
  programs.push({ name: 'Uncategorized', hue: 35, count: clients.filter(c => !c.formCategory).length });
  const weekly = [0, 0, 0, 0, 0, 0, 0];
  const weekCut = new Date(Date.now() - 7 * 864e5).toISOString().slice(0, 10);
  let weekLbs = 0, weekVisits = 0;
  visits.forEach(v => {
    if ((v.ts || '') >= weekCut) {
      const d = new Date(v.ts + 'T12:00:00');
      weekly[(d.getDay() + 6) % 7]++;
      weekVisits++; weekLbs += v.weight || 0;
    }
  });
  return {
    stats: [
      { k: 'clients', label: 'Active clients', value: clients.length, delta: 'live from database', spark: flat(clients.length) },
      { k: 'visits', label: `Visits · ${monthName}`, value: monthVisits, delta: `${visits.length} on record`, spark: flat(monthVisits) },
      { k: 'cards', label: 'Harvest cards picked', value: picked, delta: picked ? 'awaiting review' : 'all clear', spark: flat(picked) },
      { k: 'followups', label: 'No contact in 30 days', value: overdue, delta: 'follow-up candidates', spark: flat(overdue) }
    ],
    programs, weekly, weekLabels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
    weekVisits, weekLbs
  };
}

function DashboardPage({ role, openPage, push }) {
  const D = window.TRELLIS_DATA;
  const [, setTick] = React.useState(0);
  React.useEffect(() => {
    const bump = () => setTick(t => t + 1);
    const evts = ['ehcw:data:clients', 'ehcw:data:visits', 'ehcw:data:harvest', 'ehcw:data:audit', 'ehcw:user'];
    evts.forEach(e => document.addEventListener(e, bump));
    return () => evts.forEach(e => document.removeEventListener(e, bump));
  }, []);
  const me = useEhcwUser();
  const live = !!me;
  const hour = new Date().getHours();
  const daypart = hour < 12 ? 'morning' : hour < 17 ? 'afternoon' : 'evening';
  const firstName = (me?.displayName || 'June').split(' ')[0];
  const todayLine = new Date().toLocaleDateString('en-CA', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' });
  const DASH = live ? buildLiveDash(D) : D.DASH;
  const maxProg = Math.max(...DASH.programs.map(p => p.count), 1);
  const maxWeek = Math.max(...DASH.weekly, 1);
  const picked = D.HARVEST.filter(c => c.col === 'picked').slice(0, 3);
  const prioTone = { high: 'coral', med: 'gold', low: 'leaf' };
  // Caseworker load: real staff roster + live caseload counts when signed in
  const staffLoad = live
    ? window.TRELLIS_SCHEMA.EHCW_STAFF.map((s, i) => ({
        id: 'st' + i, name: s.name, initials: s.initials || s.name.split(' ').map(w => w[0]).join('').slice(0, 2),
        role: 'Caseworker', hue: (i * 47) % 360,
        clients: (D.clients || []).filter(c => (c.caseworker || '') === s.name).length
      })).sort((a, b) => b.clients - a.clients)
    : window.TRELLIS_DATA.CASEWORKERS;
  const maxLoad = Math.max(...staffLoad.map(s => s.clients), 1);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
      {/* greeting */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 16, flexWrap: 'wrap' }}>
        <div>
          <h1 style={{ fontSize: 'clamp(24px, 3.4vw, 32px)', fontWeight: 700, letterSpacing: '-0.025em' }}>Good {daypart}, {firstName}</h1>
          <p className="t-soft" style={{ margin: '6px 0 0', fontSize: 14.5 }}>{todayLine} · Everything is growing nicely.</p>
        </div>
        <Badge tone="leaf"><Icon name="shield" size={13} /> Data in Canada 🇨🇦 · all systems healthy</Badge>
      </div>

      {/* big check-in card — split actions */}
      <div className="glass" style={{
        borderRadius: 'var(--radius-l)', padding: '26px 30px', display: 'flex', alignItems: 'center', gap: 24, flexWrap: 'wrap',
        background: 'linear-gradient(135deg, oklch(0.55 0.1 160 / 0.15), oklch(0.6 0.11 96 / 0.15))',
        border: '1px solid var(--hairline-strong)',
        boxShadow: 'var(--shadow-card)', animation: 'trellis-rise .5s var(--ease-spring) 0.12s backwards'
      }}>
        <div style={{ flex: 1, minWidth: 220, textAlign: 'left', display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <Icon name="calendar" size={22} style={{ color: 'var(--leaf)' }} />
            <h2 style={{ fontSize: 'clamp(18px, 2.2vw, 22px)', fontWeight: 700, letterSpacing: '-0.02em' }}>Client Check-In</h2>
          </div>
          <p className="t-soft" style={{ fontSize: 14, lineHeight: 1.55, maxWidth: 460, margin: 0 }}>Log a repeat visit in 30 seconds, or run a full intake for someone new.</p>
        </div>
        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          <button onClick={() => openPage('checkin')} style={{
            display: 'inline-flex', alignItems: 'center', gap: 9, padding: '15px 24px', borderRadius: 15, minHeight: 50,
            fontSize: 14.5, fontWeight: 700, fontFamily: 'var(--font-display)',
            background: 'var(--accent)', color: 'var(--accent-ink)', boxShadow: 'var(--shadow-card)',
            transition: 'transform .2s var(--ease-spring)'
          }}
            onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-2px)'}
            onMouseLeave={e => e.currentTarget.style.transform = 'none'}>
            <Icon name="check" size={16} stroke={2.4} /> Check In Client
          </button>
          <button onClick={() => openPage('checkin', { flow: 'new' })} style={{
            display: 'inline-flex', alignItems: 'center', gap: 9, padding: '15px 24px', borderRadius: 15, minHeight: 50,
            fontSize: 14.5, fontWeight: 700, fontFamily: 'var(--font-display)',
            background: 'var(--hover)', color: 'var(--ink)', border: '1.5px solid var(--hairline-strong)',
            transition: 'transform .2s var(--ease-spring)'
          }}
            onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-2px)'}
            onMouseLeave={e => e.currentTarget.style.transform = 'none'}>
            <Icon name="plus" size={16} stroke={2.4} /> Register New Client
          </button>
        </div>
      </div>

      {/* stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 16 }}>
        {DASH.stats.map((s, i) => <DashStatCard key={s.k} s={s} i={i} openPage={openPage} />)}
      </div>

      {/* middle row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 16 }}>
        {/* programs */}
        <div className="glass" style={{ borderRadius: 'var(--radius-l)', padding: 24, boxShadow: 'var(--shadow-card)', display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <h3 style={{ fontSize: 16, fontWeight: 700 }}>Clients by program</h3>
            <button onClick={() => openPage('clients')} className="t-faint" style={{ fontSize: 12.5, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 4 }}>
              Database <Icon name="chevR" size={13} stroke={2.4} />
            </button>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
            {DASH.programs.map(p => (
              <button key={p.name} onClick={() => openPage('clients', { program: p.name })} title={`Open ${p.name} clients`}
                style={{ display: 'block', width: '100%', textAlign: 'left', padding: '6px 8px', borderRadius: 11, transition: 'background .15s' }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--hover)'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                <BarRow label={p.name} value={p.count} max={maxProg} hue={p.hue} />
              </button>
            ))}
          </div>
        </div>

        {/* weekly food bank */}
        <div className="glass" style={{ borderRadius: 'var(--radius-l)', padding: 24, boxShadow: 'var(--shadow-card)', display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <h3 style={{ fontSize: 16, fontWeight: 700 }}>Food bank — this week</h3>
            <button onClick={() => openPage('checkin')} className="t-faint" style={{ fontSize: 12.5, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 4 }}>
              Check-in <Icon name="chevR" size={13} stroke={2.4} />
            </button>
          </div>
          <div onClick={() => openPage('checkin', { tab: 'log' })} title="Open today's log" style={{ display: 'flex', alignItems: 'flex-end', gap: 10, height: 120, paddingTop: 8, cursor: 'pointer' }}>
            {DASH.weekly.map((v, i) => (
              <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7, height: '100%', justifyContent: 'flex-end' }}>
                <span className="mono t-faint" style={{ fontSize: 11 }}>{v}</span>
                <div style={{
                  width: '100%', maxWidth: 34, borderRadius: '8px 8px 4px 4px',
                  height: `${(v / maxWeek) * 78}%`, minHeight: 4,
                  background: i === 2 ? 'linear-gradient(180deg, oklch(0.85 0.15 96), oklch(0.74 0.14 88))' : 'var(--blue-soft)',
                  border: i === 2 ? 'none' : '1px solid var(--hairline)',
                  transition: 'height .7s var(--ease-spring)'
                }}></div>
                <span style={{ fontSize: 11, fontWeight: 700, color: i === 2 ? 'var(--ink)' : 'var(--ink-faint)' }}>{DASH.weekLabels[i]}</span>
              </div>
            ))}
          </div>
          <div className="t-faint" style={{ fontSize: 12.5 }}>{live ? <>{DASH.weekVisits} visit{DASH.weekVisits === 1 ? '' : 's'} · <strong>{DASH.weekLbs.toLocaleString()} lbs</strong> distributed this week</> : <>239 visits · <strong>5,804 lbs</strong> distributed this week</>}</div>
        </div>
      </div>

      {/* bottom row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 16 }}>
        {/* harvest preview */}
        <div className="glass" style={{ borderRadius: 'var(--radius-l)', padding: 24, boxShadow: 'var(--shadow-card)', display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <h3 style={{ fontSize: 16, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 8 }}>
              <Icon name="sprout" size={18} style={{ color: 'var(--leaf)' }} /> Today's Harvest
            </h3>
            <button onClick={() => openPage('harvest')} className="t-faint" style={{ fontSize: 12.5, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 4 }}>
              Open board <Icon name="chevR" size={13} stroke={2.4} />
            </button>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {picked.length === 0 && (
              <div className="t-faint" style={{ fontSize: 13, padding: '14px 4px', display: 'flex', alignItems: 'center', gap: 8 }}>
                <Icon name="check" size={15} style={{ color: 'var(--leaf)' }} /> Relax — nothing waiting for you.
              </div>
            )}
            {picked.map(c => (
              <button key={c.id} onClick={() => openPage('harvest', { focus: c.id })} style={{
                textAlign: 'left', padding: '12px 14px', borderRadius: 14, background: 'var(--hover)',
                border: '1px solid var(--hairline)', display: 'flex', alignItems: 'center', gap: 12, transition: 'background .2s'
              }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--active)'}
                onMouseLeave={e => e.currentTarget.style.background = 'var(--hover)'}>
                <Icon name={c.src === 'email' ? 'mail' : c.src === 'calendar' ? 'calendar' : 'spark'} size={16} style={{ color: 'var(--ink-faint)' }} />
                <span style={{ fontSize: 13.5, fontWeight: 600, flex: 1 }}>{c.title}</span>
                <Badge tone={prioTone[c.priority]}>{c.due || c.priority}</Badge>
              </button>
            ))}
          </div>
        </div>

        {/* activity / caseworkers */}
        {role === 'admin' ? (
          <div className="glass" style={{ borderRadius: 'var(--radius-l)', padding: 24, boxShadow: 'var(--shadow-card)', display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <h3 style={{ fontSize: 16, fontWeight: 700 }}>Caseworker load</h3>
              <Badge tone="plum">Admin view</Badge>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12, maxHeight: 320, overflowY: 'auto', paddingRight: 4 }}>
              {staffLoad.map(cw => (
                <button key={cw.id} onClick={() => openPage('clients', { caseworker: cw.name })} title={`Open ${cw.name}'s caseload`}
                  style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%', textAlign: 'left', padding: '6px 8px', borderRadius: 12, transition: 'background .15s' }}
                  onMouseEnter={e => e.currentTarget.style.background = 'var(--hover)'}
                  onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                  <Avatar initials={cw.initials} hue={cw.hue} size={32} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 700 }}>{cw.name}</div>
                    <div className="t-faint" style={{ fontSize: 11.5 }}>{cw.role}</div>
                  </div>
                  <div style={{ width: 90 }}>
                    <div style={{ height: 6, borderRadius: 99, background: 'var(--hover)', overflow: 'hidden' }}>
                      <div style={{ width: `${(cw.clients / maxLoad) * 100}%`, height: '100%', borderRadius: 99, background: `oklch(0.68 0.11 ${cw.hue})` }}></div>
                    </div>
                  </div>
                  <span className="mono t-faint" style={{ fontSize: 12, width: 24, textAlign: 'right' }}>{cw.clients}</span>
                </button>
              ))}
            </div>
          </div>
        ) : (
          <div className="glass" style={{ borderRadius: 'var(--radius-l)', padding: 24, boxShadow: 'var(--shadow-card)', display: 'flex', flexDirection: 'column', gap: 14 }}>
            <h3 style={{ fontSize: 16, fontWeight: 700 }}>Recent activity</h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {(D.AUDIT || []).length === 0 && (
                <div className="t-faint" style={{ fontSize: 13 }}>No activity recorded yet today.</div>
              )}
              {(D.AUDIT || []).slice(live ? 0 : 1, live ? 4 : 5).map((a, i) => (
                <div key={i} style={{ display: 'flex', gap: 12, alignItems: 'baseline' }}>
                  <span className="mono t-faint" style={{ fontSize: 11.5, width: 38, flexShrink: 0 }}>{a.t}</span>
                  <span style={{ fontSize: 13, lineHeight: 1.5 }}><strong>{a.who}</strong> — <span className="t-soft">{a.what}</span></span>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { DashboardPage });
