/* DashboardPage.jsx — "Three Acts" management overview / 看板.
   Design-system health at a glance: KPI hero row → Quality / Efficiency / Speed bands → trend.
   Every number is COMPUTED from the live globals (TOKENS/COMPONENTS/ASSETS/CHANGES/CHANGE_HISTORY/
   REQUESTS/MEMBERS/THEMES/COPY/GLOSSARY/GUIDES). No data props. */
const { useState: useStateD } = React;

const D_MONTHS = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

/* bucket shipped releases by calendar month (contiguous span only — no dead leading months) */
function monthlyEdits() {
  const m = new Map();
  (typeof CHANGE_HISTORY !== 'undefined' ? CHANGE_HISTORY : []).forEach(h => {
    const k = h.date.slice(0,7);
    m.set(k, (m.get(k)||0) + (h.items ? h.items.length : 0));
  });
  const keys = [...m.keys()].sort();
  const out = [];
  if (keys.length) {
    let [y, mo] = keys[0].split('-').map(Number);
    const end = keys[keys.length-1];
    while (true) {
      const k = `${y}-${String(mo).padStart(2,'0')}`;
      out.push({ key:k, count:m.get(k)||0, label: tr(D_MONTHS[mo-1], `${mo} 月`) });
      if (k === end) break;
      mo++; if (mo>12){ mo=1; y++; }
    }
  }
  return out;
}

/* KPI card shell */
function KpiCard({ label, value, valueColor, primary, onClick, children }) {
  return (
    <div onClick={onClick}
      className={cx('rounded-[14px] border bg-panel p-4 flex flex-col gap-1', primary?'border-accent':'border-line', onClick&&'cursor-pointer hover:bg-hover transition')}
      style={primary?{ boxShadow:'inset 0 0 0 1px var(--accent)' }:undefined}>
      <div className="text-[12px] text-ink3">{label}</div>
      <div className={cx('text-[30px] font-semibold tabular-nums leading-none', valueColor||'text-ink')}>{value}</div>
      {children}
    </div>
  );
}
function MicroBar({ segs }) { /* segs: [{w, color}] widths in % */
  return <div className="h-1 rounded-full overflow-hidden flex bg-sunken mt-1.5">{segs.filter(s=>s.w>0).map((s,i)=><div key={i} style={{ width:s.w+'%', background:s.color }} />)}</div>;
}
function Band({ label, tag, children }) {
  return (
    <div>
      <div className="flex items-baseline gap-2 mb-2.5 mt-7">
        <span className="text-[11px] font-semibold uppercase tracking-wide text-ink3">{label}</span>
        <span className="text-[12px] text-ink3">{tag}</span>
      </div>
      <div className="rounded-[14px] border border-line bg-panel p-4">{children}</div>
    </div>
  );
}
function StatTile({ label, value, valueColor, sub }) {
  return (
    <div className="flex-1 min-w-0">
      <div className="text-[12px] text-ink3">{label}</div>
      <div className={cx('text-[22px] font-semibold tabular-nums leading-tight mt-0.5', valueColor||'text-ink')}>{value}</div>
      {sub && <div className="text-[12px] text-ink2 mt-0.5">{sub}</div>}
    </div>
  );
}
function SlimBar({ pct, color, caption }) {
  return (
    <div>
      <div className="h-2 rounded-full bg-sunken overflow-hidden"><div style={{ width:Math.max(0,Math.min(100,pct))+'%', background:color }} className="h-full rounded-full" /></div>
      {caption && <div className="text-[11.5px] text-ink3 mt-1">{caption}</div>}
    </div>
  );
}
function DeltaChip({ delta }) {
  if (delta == null) return <span className="text-[12px] text-ink3">—</span>;
  const up = delta > 0, flat = delta === 0;
  const color = flat ? 'var(--text-3)' : up ? 'var(--success)' : 'var(--danger)';
  return <span className="text-[12px] font-medium tabular-nums" style={{ color }}>{flat?'±':up?'▲':'▼'}{Math.abs(delta)}%</span>;
}

function DashboardPage({ ctx, onNavigate }) {
  const [range, setRange] = useStateD('all');
  const go = (p) => onNavigate && onNavigate(p);

  const TK = typeof TOKENS!=='undefined'?TOKENS:[], CO = typeof COMPONENTS!=='undefined'?COMPONENTS:[],
        AS = typeof ASSETS!=='undefined'?ASSETS:[], CH = typeof CHANGES!=='undefined'?CHANGES:[],
        RQ = typeof REQUESTS!=='undefined'?REQUESTS:[], ME = typeof MEMBERS!=='undefined'?MEMBERS:[],
        TH = typeof THEMES!=='undefined'?THEMES:[], HIST = typeof CHANGE_HISTORY!=='undefined'?CHANGE_HISTORY:[];

  /* health */
  const tokHealthy = TK.filter(t=>t.status!=='deprecated').length;
  const cmpStable = CO.filter(c=>c.status==='stable').length;
  const cmpBeta = CO.filter(c=>c.status==='beta').length;
  const cmpDep = CO.filter(c=>c.status==='deprecated').length;
  const healthPct = Math.round((tokHealthy + cmpStable) / ((TK.length + CO.length)||1) * 100);
  const healthColor = healthPct>=80?'text-success':healthPct>=60?'text-warning':'text-danger';
  /* pending */
  const pending = CH.length;
  const major = CH.filter(c=>c.impact==='major').length;
  const minor = CH.filter(c=>c.impact==='minor').length;
  const patch = CH.filter(c=>c.impact==='patch').length;
  /* trend */
  const allMonths = monthlyEdits();
  const months = range==='6m' ? allMonths.slice(-6) : allMonths;
  const last = months[months.length-1], prev = months[months.length-2];
  const delta = prev && prev.count>0 ? Math.round((last.count-prev.count)/prev.count*100) : null;
  const maxC = Math.max(1, ...months.map(d=>d.count));
  /* requirements */
  const reqOpen = RQ.filter(r=>r.status==='open').length;
  const reqResolved = RQ.filter(r=>r.status==='resolved').length;
  const reqTotal = RQ.length || 1;
  const unanswered = RQ.filter(r=>r.status==='open' && (r.replies||[]).length===0).length;
  /* quality detail */
  const caution = CO.filter(c=>c.caution).length;
  const drafts = CO.filter(c=>c.hasDraft).length;
  const deprecated = cmpDep + TK.filter(t=>t.status==='deprecated').length;
  const debtPct = Math.round(deprecated / ((TK.length+CO.length)||1) * 100);
  /* efficiency detail */
  const usedCount = AS.filter(a=>(a.used||0)>0).length;
  const orphans = AS.filter(a=>(a.used||0)===0).length;
  /* cadence */
  const sorted = [...HIST].sort((a,b)=>a.date<b.date?-1:1);
  const cadenceDays = sorted.length>1 ? Math.round((new Date(sorted[sorted.length-1].date)-new Date(sorted[0].date))/86400000/(sorted.length-1)) : null;
  /* members roles */
  const mgr = ME.filter(m=>m.role==='manager').length, ed = ME.filter(m=>m.role==='editor').length, vw = ME.filter(m=>m.role==='viewer').length;

  return (
    <div className="h-full flex flex-col bg-app">
      <PageToolbar title={tr('Dashboard','看板')} subtitle={tr('Design-system health at a glance','设计系统健康概览')}
        facets={<Segmented size="sm" value={range} onChange={setRange} options={[{value:'6m',label:tr('6M','近 6 月')},{value:'all',label:tr('All','全部')}]} />} />
      <div className="flex-1 overflow-y-auto ds-scroll [scrollbar-gutter:stable]">
        <div className="max-w-[1080px] mx-auto px-6 py-5">

          {/* KPI HERO ROW */}
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
            <KpiCard primary label={tr('System health','系统健康度')} value={healthPct+'%'} valueColor={healthColor}>
              <div className="text-[12px] text-ink2">{tr(`${cmpStable}/${CO.length} components stable`,`${cmpStable}/${CO.length} 组件稳定`)}</div>
              <MicroBar segs={[
                { w: cmpStable/(CO.length||1)*100, color:'var(--success)' },
                { w: cmpBeta/(CO.length||1)*100, color:'var(--warning)' },
                { w: cmpDep/(CO.length||1)*100, color:'var(--text-3)' },
              ]} />
            </KpiCard>

            <KpiCard label={tr('Pending review','待审核')} value={pending} onClick={()=>go('changes')}>
              <div className="text-[12px] text-ink2">
                {major>0 ? <span style={{ color:'var(--danger)' }} className="font-medium">{tr(`${major} major`,`${major} 项重大`)}</span>
                  : tr(`${minor} minor · ${patch} patch`,`${minor} 改 · ${patch} 修`)}
              </div>
            </KpiCard>

            <KpiCard label={tr('Edits · '+(last?last.label:'—'),'改动 · '+(last?last.label:'—'))} value={last?last.count:0}>
              <div className="text-[12px] text-ink2 flex items-center gap-2">{tr('vs prior month','较上月')} <DeltaChip delta={delta} /></div>
            </KpiCard>

            <KpiCard label={tr('Open requirements','待办需求')} value={reqOpen} onClick={()=>go('requirements')}>
              <div className="text-[12px] text-ink2">{tr(`${reqResolved} resolved of ${RQ.length}`,`已解决 ${reqResolved}/${RQ.length}`)}</div>
              <MicroBar segs={[{ w: reqResolved/reqTotal*100, color:'var(--success)' }]} />
            </KpiCard>
          </div>

          {/* ACT I — Quality */}
          <Band label={tr('Quality','品质')} tag={tr('Is it production-ready?','是否可投产?')}>
            <div className="flex gap-4 mb-4">
              <StatTile label={tr('Stable share','稳定占比')} value={Math.round(cmpStable/(CO.length||1)*100)+'%'} valueColor="text-success"
                sub={tr(`${caution} caution · ${drafts} drafts`,`${caution} 谨慎 · ${drafts} 草稿`)} />
              <StatTile label={tr('Deprecation debt','废弃负债')} value={debtPct+'%'} valueColor={deprecated>0?'text-ink2':'text-ink3'}
                sub={tr(`${deprecated} deprecated tokens / components`,`${deprecated} 个废弃 token/组件`)} />
            </div>
            <div className="h-2.5 rounded-full overflow-hidden flex bg-sunken">
              {[['stable',cmpStable,'var(--success)'],['beta',cmpBeta,'var(--warning)'],['deprecated',cmpDep,'var(--text-3)']].map(([k,n,c])=> n>0 ?
                <div key={k} style={{ width:n/(CO.length||1)*100+'%', background:c }} title={`${k}: ${n}`} /> : null)}
            </div>
            <div className="flex items-center gap-4 mt-2.5">
              <span className="inline-flex items-center gap-1.5"><CompStatusTag status="stable" size="sm" /><CountBadge n={cmpStable} tone="muted" /></span>
              <span className="inline-flex items-center gap-1.5"><CompStatusTag status="beta" size="sm" /><CountBadge n={cmpBeta} tone="muted" /></span>
              <span className="inline-flex items-center gap-1.5"><CompStatusTag status="deprecated" size="sm" /><span className="text-[12px] text-ink3 tabular-nums">{cmpDep}</span></span>
              <button onClick={()=>go('components')} className="ml-auto text-[12px] text-accent hover:underline">{tr('View components →','查看组件 →')}</button>
            </div>
          </Band>

          {/* ACT II — Efficiency */}
          <Band label={tr('Efficiency','效率')} tag={tr('Are we keeping up, and is it lean?','是否跟得上、是否精简?')}>
            <div className="flex gap-4 mb-4">
              <StatTile label={tr('Resolution rate','解决率')} value={Math.round(reqResolved/reqTotal*100)+'%'} valueColor="text-success"
                sub={tr(`${reqOpen} open · ${unanswered} unanswered`,`${reqOpen} 待办 · ${unanswered} 未回复`)} />
              <StatTile label={tr('Asset reuse','资源复用')} value={Math.round(usedCount/(AS.length||1)*100)+'%'}
                sub={orphans>0 ? <span style={{color:'var(--warning)'}}>{tr(`${orphans} orphan asset${orphans>1?'s':''}`,`${orphans} 个未引用资源`)}</span> : tr('all assets referenced','全部已被引用')} />
            </div>
            <div className="flex flex-col gap-3">
              <SlimBar pct={reqResolved/reqTotal*100} color="var(--success)" caption={tr(`Requirements · ${reqResolved} resolved / ${reqOpen} open`,`需求 · 已解决 ${reqResolved} / 待办 ${reqOpen}`)} />
              <SlimBar pct={usedCount/(AS.length||1)*100} color="var(--accent)" caption={tr(`Assets · ${usedCount} referenced / ${orphans} orphan`,`资源 · 已引用 ${usedCount} / 未引用 ${orphans}`)} />
            </div>
          </Band>

          {/* ACT III — Speed */}
          <Band label={tr('Speed','速度')} tag={tr('Are we moving?','是否在推进?')}>
            <div className="flex items-end justify-between gap-4 mb-4">
              <StatTile label={tr('Momentum','势头')} value={<span className="inline-flex items-center gap-1.5">{last?last.count:0} <DeltaChip delta={delta} /></span>}
                sub={cadenceDays!=null ? tr(`ships every ~${cadenceDays} days · ${HIST.length} releases`,`约每 ${cadenceDays} 天发布一次 · 共 ${HIST.length} 次`) : tr(`${HIST.length} release`,`${HIST.length} 次发布`)} />
            </div>
            {months.length===0 ? <EmptyState icon="clock" title={tr('No releases yet','暂无发版')} /> : (
              <div>
                <div className="flex items-end gap-3 h-[120px]">
                  {months.map((d,i)=>{ const isLast=i===months.length-1; return (
                    <div key={d.key} className="flex-1 flex flex-col items-center justify-end gap-1.5">
                      <div title={`${d.label}: ${d.count}`} className="w-full rounded-t-[5px]" style={{ height:Math.max(2, d.count/maxC*100)+'%', background:isLast?'var(--accent)':'color-mix(in srgb, var(--accent) 38%, transparent)' }} />
                      <span className="text-[12px] tabular-nums text-ink">{d.count}</span>
                      <span className="text-[11px] text-ink3">{d.label}</span>
                    </div>
                  );})}
                </div>
                <div className="border-t border-line mt-1.5 pt-2 text-[11.5px] text-ink3">{tr('Edits shipped per month','每月发布的改动数')}</div>
              </div>
            )}
          </Band>

          {/* system library — registry counts as cards, consistent with the hero KPIs */}
          <div className="flex items-baseline gap-2 mb-2.5 mt-7">
            <span className="text-[11px] font-semibold uppercase tracking-wide text-ink3">{tr('Library','资源概览')}</span>
            <span className="text-[12px] text-ink3">{tr('What the system contains','系统包含的内容')}</span>
          </div>
          <div className="grid grid-cols-3 sm:grid-cols-4 lg:grid-cols-7 gap-3">
            {[
              [TH.length, tr('Themes','主题'), 'sliders', null, 'themes'],
              [TK.length, tr('Tokens','Token'), 'layers', null, 'tokens'],
              [AS.length, tr('Assets','资源'), 'grid', null, 'assets'],
              [(typeof COPY!=='undefined'?COPY.length:0), tr('Copy','文案'), 'edit', null, 'content'],
              [(typeof GLOSSARY!=='undefined'?GLOSSARY.length:0), tr('Terms','术语'), 'hash', null, 'content'],
              [(typeof GUIDES!=='undefined'?GUIDES.length:0), tr('Guides','规范'), 'eye', null, 'content'],
              [ME.length, tr('Members','成员'), 'user', `${mgr}·${ed}·${vw}`, 'members'],
            ].map(([n,label,ic,sub,dest],i)=>(
              <div key={i} onClick={dest?()=>go(dest):undefined}
                className={cx('rounded-[12px] border border-line bg-panel p-3 flex flex-col gap-1', dest&&'cursor-pointer hover:bg-hover transition')}>
                <div className="flex items-center gap-1.5 text-ink3"><Icon name={ic} size={13} /><span className="text-[11.5px]">{label}</span></div>
                <div className="text-[22px] font-semibold text-ink tabular-nums leading-none">{n}</div>
                {sub && <div className="text-[11px] text-ink3">{sub}</div>}
              </div>
            ))}
          </div>
          <div className="h-2" />
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DashboardPage });
