// Screen: Command Center — the hero
function CommandCenter({ scope, setScope, go, nav }) {
  const { useState } = React;
  const [period, setPeriod] = useState(30);
  const [compare, setCompare] = useState(true);

  const stores = STORES;

  // Period revenue per store + combined
  const revs = Object.fromEntries(stores.map(s => [s.id, revFor(s.id, period)]));
  const combined = stores.reduce((a, s) => a + revs[s.id], 0);
  const combinedPrev = stores.reduce((a, s) => a + revs[s.id] / (1 + deltaFor(s.id, period) / 100), 0);
  const combinedDelta = ((combined - combinedPrev) / combinedPrev) * 100;

  const active = scope === 'all' ? stores : stores.filter(s => s.id === scope);
  const totalScripts = active.reduce((a, s) => a + s.scriptsToday, 0);
  const totalQueue = active.reduce((a, s) => a + s.inQueue, 0);

  const series = stores.map((s, i) => ({
    name: s.tag, data: s.spark,
    color: ['var(--moss)', '#a8652f', '#5b6b8c'][i],
    bold: i === 0,
  }));

  return (
    <div className="content" data-screen-label="Command Center">

      {/* Period controls */}
      <div className="cc-controls">
        <span className="lbl">Period</span>
        <div className="filt">
          {PERIOD_OPTS.map(d => (
            <button key={d} className={period === d ? 'on' : ''} onClick={() => setPeriod(d)}>
              Last {d}
            </button>
          ))}
        </div>
        <button className={'cmp-toggle' + (compare ? ' on' : '')} onClick={() => setCompare(!compare)}>
          <span className="box">{compare ? '✓' : ''}</span>
          Compare to previous period
        </button>
        <span style={{ marginLeft: 'auto', fontSize: 12.5, color: 'var(--ink-3)' }}>
          {compare ? `vs the ${period} days before` : 'comparison off'}
        </span>
      </div>

      {/* Topline — combined revenue, all locations */}
      <div className="card card-pad" style={{ display: 'flex', alignItems: 'baseline', gap: 28, padding: '18px 22px' }}>
        <div>
          <div className="kicker">Combined revenue · all locations · last {period} days</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
            <span className="big-num" style={{ fontSize: 40 }}>{fmtMoney(combined)}</span>
            {compare ? <Delta value={combinedDelta}></Delta> : null}
            {compare ? (
              <span style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>
                prev. {fmtMoney(combinedPrev)}
              </span>
            ) : null}
          </div>
        </div>
        <div style={{ borderLeft: '1px solid var(--line-2)', paddingLeft: 24 }}>
          <div className="kicker">Scripts today</div>
          <div className="big-num" style={{ fontSize: 28 }}>{totalScripts}</div>
        </div>
        <div style={{ borderLeft: '1px solid var(--line-2)', paddingLeft: 24 }}>
          <div className="kicker">In queue now</div>
          <div className="big-num" style={{ fontSize: 28 }}>{totalQueue}</div>
        </div>
        <div style={{ borderLeft: '1px solid var(--line-2)', paddingLeft: 24 }}>
          <div className="kicker">Compounds in lab</div>
          <div className="big-num" style={{ fontSize: 28 }}>7</div>
        </div>
        <div style={{ marginLeft: 'auto', textAlign: 'right' }}>
          <div className="kicker">All systems</div>
          <span className="badge ok">● Reporting current · 6:58a</span>
        </div>
      </div>

      {/* Three stores */}
      <div>
        <SectionHead title="Locations" action="Fill queue →" onAction={() => go('queue')}></SectionHead>
        <div className="loc-grid" style={{ marginTop: 10 }}>
          {stores.map(s => {
            const dimmed = scope !== 'all' && scope !== s.id;
            const busy = s.waitMin >= 15;
            return (
              <div key={s.id} className={'card loc-card' + (dimmed ? ' dim' : '')}
                onClick={() => setScope(scope === s.id ? 'all' : s.id)} style={{ cursor: 'pointer' }}>
                <div className="loc-head">
                  <span className="name">{s.name}</span>
                  <span className="status">
                    {busy
                      ? <span className="badge warn">Queue {s.waitMin} min</span>
                      : <span className="badge ok">On pace</span>}
                  </span>
                </div>
                <div className="loc-sub">{s.sub}</div>
                <div className="loc-rev">
                  <span className="big-num">{fmtMoney(revs[s.id])}</span>
                  {compare ? <Delta value={deltaFor(s.id, period)}></Delta> : null}
                </div>
                <div className="kicker" style={{ marginTop: 1 }}>revenue · last {period} days</div>
                <div style={{ margin: '10px 0 0' }}>
                  <Spark data={s.spark} w={300} h={36} color={busy ? '#a8652f' : 'var(--moss)'}></Spark>
                </div>
                <div className="loc-stats">
                  <div className="loc-stat">
                    <div className="v">{s.scriptsToday}</div>
                    <div className="k">scripts today</div>
                  </div>
                  <div className="loc-stat">
                    <div className="v">{s.inQueue}</div>
                    <div className="k">in queue</div>
                  </div>
                  <div className="loc-stat">
                    <div className="v">{Math.round(s.compShare * 100)}%</div>
                    <div className="k">compounding</div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Trend + margin story */}
      <div className="cc-row">
        <div className="card card-pad">
          <SectionHead title="Weekly revenue · trailing 12 weeks · $k"></SectionHead>
          <div style={{ marginTop: 14 }}>
            <TrendChart series={series} labels={TREND_LABELS}></TrendChart>
          </div>
        </div>

        <div className="card card-pad margin-story">
          <SectionHead title="Where the profit lives"></SectionHead>
          <div className="margin-pair">
            <div className="margin-cell comp">
              <div className="kicker" style={{ color: 'var(--moss)' }}>Compounding</div>
              <div className="big-num">{pct(MARGIN_STORY.compounding.margin)}</div>
              <div className="lbl">gross margin · {fmtK(MARGIN_STORY.compounding.gp)} GP MTD</div>
              <div className="margin-bar"><i style={{ width: '58.4%', background: 'var(--moss)' }}></i></div>
            </div>
            <div className="margin-cell">
              <div className="kicker">Retail</div>
              <div className="big-num" style={{ color: 'var(--ink-2)' }}>{pct(MARGIN_STORY.retail.margin)}</div>
              <div className="lbl">gross margin · {fmtK(MARGIN_STORY.retail.gp)} GP MTD</div>
              <div className="margin-bar"><i style={{ width: '17.2%', background: 'var(--ink-3)' }}></i></div>
            </div>
          </div>
          <div className="margin-note">
            The lab is <b>18% of revenue</b> and <b>42% of gross profit</b>. Every point of
            compounding share you add at Anacortes is worth three of retail.
          </div>
        </div>
      </div>

      {/* Alerts */}
      <div>
        <SectionHead title="Needs your attention" action="Insights →" onAction={() => go('insights')}></SectionHead>
        <div className="card alert-strip" style={{ marginTop: 10 }}>
          {ALERTS.map((a, i) => (
            <div className={'alert-row' + (a.link ? ' click' : '')} key={i}
              onClick={a.link ? () => nav.goQueue(a.link) : undefined}>
              <span className={'sev ' + a.sev}></span>
              <span className="storetag">{a.store}</span>
              <span>{a.text}</span>
              {a.link ? <span className="golink">View →</span> : null}
              <span className="t">{a.time}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CommandCenter });
