// screens.jsx — Dashboard, Budget, Providers
const { useState: useS2 } = React;

// ── Greeting header used across screens ─────────────────────────────
function PageHead({ title, sub, right }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 20, marginBottom: 26, flexWrap: 'wrap' }}>
      <div>
        <h1 style={{ margin: 0, fontFamily: 'var(--serif)', fontWeight: 500, fontSize: 32, letterSpacing: '-.02em', color: 'var(--ink)' }}>{title}</h1>
        {sub && <p style={{ margin: '6px 0 0', fontSize: 15, color: 'var(--ink-2)', maxWidth: 620, lineHeight: 1.5 }}>{sub}</p>}
      </div>
      {right}
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════
// DASHBOARD
// ══════════════════════════════════════════════════════════════════
function Dashboard({ go }) {
  const S = useHaven();
  const plan = S.plan;
  const hr = TODAY.getHours();
  const greet = hr < 12 ? 'Good morning' : hr < 18 ? 'Good afternoon' : 'Good evening';
  const remaining = useCountUp(plan.remaining);
  const pacing = plan.pct - PLAN_TIME_PCT; // + = ahead of pace (spending faster)

  const quick = [
    { label: 'Log a claim', icon: 'receipt', variant: 'primary', go: () => go('claims', 'new') },
    { label: 'Add an invoice', icon: 'upload', variant: 'white', go: () => go('invoices', 'add') },
    { label: 'Pay a worker', icon: 'people', variant: 'white', go: () => go('workers') },
    { label: 'Review prep', icon: 'sparkles', variant: 'white', go: () => go('review') },
  ];

  return (
    <div className="fade-in">
      <PageHead
        title={<span>{greet}, {S.doc.child.parent || 'there'}<span style={{ color: 'var(--primary)' }}>.</span></span>}
        sub={<span>Here's where {S.doc.child.name}'s plan stands today, {fmtDate(TODAY)}. A few small things need you — nothing urgent.</span>}
      />

      {/* quick actions */}
      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 26 }}>
        {quick.map((q) => (
          <Button key={q.label} variant={q.variant} icon={Icons[q.icon]} onClick={q.go}>{q.label}</Button>
        ))}
      </div>

      {/* money at a glance */}
      <Card pad={26} style={{ marginBottom: 22 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: 36, alignItems: 'center' }}>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14, paddingRight: 36, borderRight: '1px solid var(--line)' }}>
            <Ring pct={plan.pct} size={148} stroke={15} color="var(--primary)">
              <span style={{ fontSize: 12.5, color: 'var(--ink-2)', fontWeight: 600 }}>remaining</span>
              <span style={{ fontSize: 26, fontWeight: 700, letterSpacing: '-.02em', fontVariantNumeric: 'tabular-nums' }}>{fmtMoney(remaining)}</span>
              <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>of {fmtMoney(plan.total)}</span>
            </Ring>
            <Pill color="var(--ink-2)" bg="var(--surface-2)"><Icons.calendar size={13} />{PLAN_DAYS_LEFT} days left in plan</Pill>
          </div>

          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 18, gap: 12 }}>
              <h2 style={{ margin: 0, fontFamily: 'var(--serif)', fontWeight: 500, fontSize: 20, whiteSpace: 'nowrap' }}>Money at a glance</h2>
              <button onClick={() => go('budget')} style={{ background: 'none', border: 'none', color: 'var(--primary-ink)', fontWeight: 600, fontSize: 13.5, display: 'inline-flex', alignItems: 'center', gap: 3, whiteSpace: 'nowrap' }}>See full budget <Icons.chevR size={15} /></button>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 17 }}>
              {S.doc.budget.map((c) => {
                const over = c.pct > PLAN_TIME_PCT + 0.06;
                return (
                  <div key={c.key} style={{ display: 'grid', gridTemplateColumns: '1fr auto', columnGap: 16, rowGap: 8, alignItems: 'baseline' }}>
                    <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontWeight: 600, fontSize: 13.5, minWidth: 0 }}>
                      <span style={{ width: 9, height: 9, borderRadius: 3, background: c.color, flexShrink: 0 }} />
                      <span style={{ whiteSpace: 'nowrap' }}>{c.name}</span>
                      {over && <Pill color="var(--amber-ink)" bg="var(--amber-soft)" style={{ fontSize: 11, padding: '2px 7px' }}>{Math.round(c.pct * 100)}% used</Pill>}
                    </span>
                    <span style={{ color: 'var(--ink-2)', fontVariantNumeric: 'tabular-nums', fontSize: 13.5, whiteSpace: 'nowrap' }}><b style={{ color: 'var(--ink)' }}>{fmtMoney(c.remaining)}</b> left</span>
                    <div style={{ gridColumn: '1 / -1' }}><Bar pct={c.pct} color={c.color} marker={PLAN_TIME_PCT} /></div>
                  </div>
                );
              })}
            </div>
            <div style={{ marginTop: 16 }}>
              <Note tone={pacing > 0.05 ? 'amber' : 'good'} icon={pacing > 0.05 ? 'info' : 'checkCircle'}>
                {pacing > 0.05
                  ? <>You're spending a little faster than the calendar — you've used {Math.round(plan.pct * 100)}% of funds and {Math.round(PLAN_TIME_PCT * 100)}% of the plan year has passed. The marker line shows where you'd be "on pace". Worth a glance, not a worry.</>
                  : <>You're tracking nicely — spending is roughly in step with how much of the plan year has gone by.</>}
              </Note>
            </div>
          </div>
        </div>
      </Card>

      {/* two columns: needs you + activity */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.35fr 1fr', gap: 22, alignItems: 'start' }}>
        <div>
          <SectionTitle sub="Gentle nudges so nothing slips through.">Needs you</SectionTitle>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {S.reminders.map((r) => <ReminderCard key={r.id} r={r} go={go} />)}
          </div>
        </div>
        <div>
          <SectionTitle sub="Everything you've done lately.">Recent activity</SectionTitle>
          <Card pad={8}>
            {S.doc.activity.length === 0 && <div style={{ padding: 28, textAlign: 'center', color: 'var(--ink-3)', fontSize: 13.5 }}>Nothing yet — what you do in Haven will show up here.</div>}
            {S.doc.activity.map((a, i, arr) => {
              const tone = { paid: 'var(--good)', claim: 'var(--primary)', invoice: 'var(--amber-ink)', pay: 'var(--core)' }[a.type];
              const ic = { paid: 'checkCircle', claim: 'send', invoice: 'receipt', pay: 'people' }[a.type];
              const I = Icons[ic];
              return (
                <div key={a.id} style={{ display: 'flex', gap: 12, padding: '12px 13px', borderBottom: i < arr.length - 1 ? '1px solid var(--line)' : 'none', alignItems: 'center' }}>
                  <span style={{ color: tone, background: 'var(--surface-2)', borderRadius: 9, padding: 7, display: 'grid', placeItems: 'center' }}><I size={17} /></span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, lineHeight: 1.35 }}>{a.text}</div>
                    <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{fmtDateShort(a.date)}</div>
                  </div>
                  <span style={{ fontSize: 13.5, fontWeight: 600, fontVariantNumeric: 'tabular-nums', color: a.type === 'paid' ? 'var(--good)' : 'var(--ink)' }}>
                    {a.type === 'paid' ? '+' : ''}{fmtMoney(a.amount, 2)}
                  </span>
                </div>
              );
            })}
          </Card>
        </div>
      </div>
    </div>
  );
}

function ReminderCard({ r, go }) {
  const tones = {
    amber: { bar: 'var(--amber)', ic: 'var(--amber-ink)', icbg: 'var(--amber-soft)' },
    alert: { bar: 'var(--alert)', ic: 'var(--alert)', icbg: 'var(--alert-soft)' },
    primary: { bar: 'var(--primary)', ic: 'var(--primary)', icbg: 'var(--primary-soft)' },
  }[r.tone];
  const I = Icons[r.icon];
  return (
    <Card pad={0} hover onClick={() => go(r.to)} style={{ overflow: 'hidden', display: 'flex' }}>
      <div style={{ width: 5, background: tones.bar, flexShrink: 0 }} />
      <div style={{ display: 'flex', gap: 14, padding: '16px 18px', alignItems: 'center', flex: 1 }}>
        <span style={{ color: tones.ic, background: tones.icbg, borderRadius: 12, padding: 11, display: 'grid', placeItems: 'center', flexShrink: 0 }}><I size={22} /></span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 15.5, marginBottom: 2 }}>{r.title}</div>
          <div style={{ fontSize: 13.5, color: 'var(--ink-2)', lineHeight: 1.45 }}>{r.body}</div>
        </div>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, color: 'var(--primary-ink)', fontWeight: 600, fontSize: 13.5, flexShrink: 0 }}>{r.cta}<Icons.chevR size={16} /></span>
      </div>
    </Card>
  );
}

// ══════════════════════════════════════════════════════════════════
// BUDGET
// ══════════════════════════════════════════════════════════════════
// month-by-month spending: claims (not bounced) + paid worker hours
function monthlySpend(S) {
  const start = new Date(PLAN_START);
  const end = TODAY < PLAN_END ? TODAY : PLAN_END;
  const months = [];
  const d = new Date(start.getFullYear(), start.getMonth(), 1);
  while (d <= end) {
    months.push({ key: d.getFullYear() + '-' + (d.getMonth() + 1), label: d.toLocaleDateString('en-AU', { month: 'short' }), perCat: {}, total: 0 });
    d.setMonth(d.getMonth() + 1);
  }
  const idx = {};
  months.forEach((m) => { idx[m.key] = m; });
  const add = (dateStr, cat, amt) => {
    const dd = new Date(dateStr);
    const m = idx[dd.getFullYear() + '-' + (dd.getMonth() + 1)];
    if (m && amt > 0) { m.perCat[cat] = (m.perCat[cat] || 0) + amt; m.total += amt; }
  };
  S.doc.claims.forEach((c) => { if (c.status !== 'rejected') add(c.date, c.cat, c.amount); });
  S.doc.timesheets.forEach((t) => {
    if (t.status === 'paid') { const w = S.doc.workers.find((x) => x.id === t.worker); if (w) add(t.date, 'core', t.hours * w.rate); }
  });
  return months;
}

function SpendChart({ S }) {
  const months = monthlySpend(S);
  const maxT = Math.max.apply(null, months.map((m) => m.total).concat([1]));
  const hasAny = months.some((m) => m.total > 0);
  return (
    <Card pad={22}>
      {!hasAny && <div style={{ textAlign: 'center', color: 'var(--ink-3)', fontSize: 13.5, padding: '30px 0' }}>No spending recorded yet — the chart fills in as you log claims and pay workers.</div>}
      {hasAny && (
        <div>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8, height: 175 }}>
            {months.map((m) => (
              <div key={m.key} title={m.label + ': ' + fmtMoney(m.total)} style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', height: '100%' }}>
                {m.total > 0 && <div style={{ fontSize: 11, textAlign: 'center', color: 'var(--ink-3)', marginBottom: 4, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>{m.total >= 1000 ? '$' + (m.total / 1000).toFixed(1) + 'k' : fmtMoney(m.total)}</div>}
                {S.doc.budget.map((c) => {
                  const v = m.perCat[c.key] || 0;
                  if (!v) return null;
                  return <div key={c.key} style={{ height: Math.max(3, (v / maxT) * 140), background: c.color, borderRadius: 3, marginTop: 2 }}></div>;
                })}
              </div>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 6, borderTop: '1px solid var(--line)', paddingTop: 7 }}>
            {months.map((m) => <div key={m.key} style={{ flex: 1, textAlign: 'center', fontSize: 11.5, color: 'var(--ink-3)' }}>{m.label}</div>)}
          </div>
          <div style={{ display: 'flex', gap: 16, marginTop: 14, flexWrap: 'wrap' }}>
            {S.doc.budget.map((c) => (
              <span key={c.key} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12.5, color: 'var(--ink-2)', fontWeight: 600 }}>
                <span style={{ width: 9, height: 9, borderRadius: 3, background: c.color }}></span>{c.name}
              </span>
            ))}
          </div>
        </div>
      )}
    </Card>
  );
}

function Budget() {
  const S = useHaven();
  const plan = S.plan;
  const [open, setOpen] = useS2('capacity');
  return (
    <div className="fade-in">
      <PageHead title="Budget" sub={<>How {S.doc.child.name}'s funding is split, what's left, and whether you're on pace. The faint line on each bar is where you'd be if you spent evenly across the year.</>} />

      {/* summary strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 14, marginBottom: 24 }}>
        {[
          { label: 'Total funded', val: fmtMoney(plan.total), foot: fmtDate(PLAN_START) + ' – ' + fmtDate(PLAN_END) },
          { label: 'Spent so far', val: fmtMoney(plan.spent), foot: Math.round(plan.pct * 100) + '% of plan' },
          { label: 'Remaining', val: fmtMoney(plan.remaining), foot: 'across all categories', accent: true },
          { label: 'Days left', val: PLAN_DAYS_LEFT, foot: Math.round((1 - PLAN_TIME_PCT) * 100) + '% of year to go' },
        ].map((s) => (
          <Card key={s.label} pad={18}>
            <div style={{ fontSize: 13, color: 'var(--ink-2)', fontWeight: 600, marginBottom: 6 }}>{s.label}</div>
            <div style={{ fontSize: 26, fontWeight: 700, letterSpacing: '-.02em', fontVariantNumeric: 'tabular-nums', color: s.accent ? 'var(--primary)' : 'var(--ink)' }}>{s.val}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 4 }}>{s.foot}</div>
          </Card>
        ))}
      </div>

      <div style={{ marginBottom: 26 }}>
        <SectionTitle sub="Claims and worker pays, month by month across the plan year.">Spending over time</SectionTitle>
        <SpendChart S={S} />
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {S.doc.budget.map((c) => {
          const isOpen = open === c.key;
          const over = c.pct > PLAN_TIME_PCT + 0.06;
          return (
            <Card key={c.key} pad={0} style={{ overflow: 'hidden' }}>
              <div onClick={() => setOpen(isOpen ? null : c.key)} style={{ display: 'flex', alignItems: 'center', gap: 18, padding: '20px 24px', cursor: 'pointer' }}>
                <Ring pct={c.pct} size={64} stroke={8} color={c.color}>
                  <span style={{ fontSize: 14, fontWeight: 700 }}>{Math.round(c.pct * 100)}%</span>
                </Ring>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 9, flexWrap: 'wrap' }}>
                    <h3 style={{ margin: 0, fontSize: 18, fontWeight: 700, whiteSpace: 'nowrap' }}>
                      <PlainTip term={c.name} />
                    </h3>
                    {over && <Pill color="var(--amber-ink)" bg="var(--amber-soft)"><Icons.info size={13} />Spending ahead of pace</Pill>}
                  </div>
                  <div style={{ maxWidth: 560 }}><Bar pct={c.pct} color={c.color} marker={PLAN_TIME_PCT} height={8} /></div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontSize: 21, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{fmtMoney(c.remaining)}</div>
                  <div style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>left of {fmtMoney(c.budget)}</div>
                </div>
                <span style={{ color: 'var(--ink-3)', transform: isOpen ? 'rotate(180deg)' : 'none', transition: 'transform .2s' }}><Icons.chevD size={20} /></span>
              </div>
              {isOpen && (
                <div style={{ padding: '0 24px 22px 24px', animation: 'fadeIn .25s ease both' }}>
                  <div style={{ marginBottom: 16 }}><Note tone="info" icon="info">{c.plain}</Note></div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                    {c.subs.map((s) => (
                      <div key={s.name} style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: '4px 20px', alignItems: 'center' }}>
                        <div style={{ fontSize: 14, fontWeight: 600 }}>{s.name}</div>
                        <div style={{ fontSize: 13, color: 'var(--ink-2)', textAlign: 'right', fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>
                          {fmtMoney(s.spent)} <span style={{ color: 'var(--ink-3)' }}>/ {fmtMoney(s.budget)}</span>
                        </div>
                        <div style={{ gridColumn: '1 / -1' }}><Bar pct={s.pct} color={c.color} track="var(--surface-2)" height={7} marker={PLAN_TIME_PCT} /></div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </Card>
          );
        })}
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════
// PROVIDERS
// ══════════════════════════════════════════════════════════════════
function Providers() {
  const S = useHaven();
  return (
    <div className="fade-in">
      <PageHead title="Providers & agreements" sub={<>Everyone you buy supports from, their rates, and when each <PlainTip term="Service agreement" /> needs renewing.</>} />
      {S.doc.providers.length === 0 && <Note tone="info" icon="info">No providers yet — add your therapists, programs and suppliers in <b>Settings</b> and they'll appear here and in the claim form.</Note>}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(330px, 1fr))', gap: 14 }}>
        {S.doc.providers.map((p) => {
          const days = p.agreementEnds ? daysBetween(TODAY, new Date(p.agreementEnds)) : null;
          const soon = days != null && days <= 21;
          const cat = S.doc.budget.find((b) => b.key === p.cat);
          return (
            <Card key={p.id} hover pad={20}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12, gap: 12 }}>
                <Avatar initials={p.short.split(' ').map((w) => w[0]).slice(0, 2).join('')} bg={cat.soft} color={cat.color} size={44} />
                {p.agreementEnds
                  ? <Pill color={soon ? 'var(--alert)' : 'var(--ink-2)'} bg={soon ? 'var(--alert-soft)' : 'var(--surface-2)'}>{soon ? <Icons.alert size={13} /> : <Icons.calendar size={13} />}{soon ? `Ends in ${days}d` : 'Agreement active'}</Pill>
                  : <Pill>No agreement</Pill>}
              </div>
              <h3 style={{ margin: '0 0 4px', fontSize: 16.5, fontWeight: 700, lineHeight: 1.25 }}>{p.name}</h3>
              <div style={{ fontSize: 13, color: 'var(--ink-2)', marginBottom: 14 }}>{p.sub}</div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 13.5, borderTop: '1px solid var(--line)', paddingTop: 12 }}>
                <span style={{ color: 'var(--ink-2)' }}>Rate <b style={{ color: 'var(--ink)' }}>{p.rate}</b></span>
                {p.agreementEnds && <span style={{ color: soon ? 'var(--alert)' : 'var(--ink-2)' }}>Renews {fmtDateShort(p.agreementEnds)}</span>}
              </div>
              <div style={{ marginTop: 11 }}>
                {p.agreementFile && p.agreementFile.url ? (
                  <a href={p.agreementFile.url} target="_blank" rel="noopener" style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13, fontWeight: 600, color: 'var(--primary-ink)', textDecoration: 'none' }}>
                    <Icons.doc size={15} />Open the agreement
                  </a>
                ) : (
                  <label style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13, fontWeight: 600, color: 'var(--ink-3)', cursor: 'pointer' }}>
                    <input type="file" accept=".pdf,.png,.jpg,.jpeg,.heic,.webp" style={{ display: 'none' }} onChange={async (e) => { const fl = e.target.files && e.target.files[0]; e.target.value = ''; if (!fl) return; try { const r = await Store.uploadFile(fl); S.listPatch('providers', p.id, { agreementFile: { name: r.name, url: r.url } }); } catch (err) { alert("Couldn't store the file — is the NAS reachable?"); } }} />
                    <Icons.paperclip size={15} />Attach the agreement…
                  </label>
                )}
              </div>
            </Card>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard, Budget, Providers, PageHead, ReminderCard });
