// Bellia — Dashboard (variante B : nav pill flottante + hero CA orange + KPI grid)

const ALERTS = [
  { kind: 'err',  agent: 'Comptabilité', t: 'Food cost en dérive : 32 % vs cible 28 %', age: 'il y a 2 h' },
  { kind: 'warn', agent: 'Fournisseurs',  t: '4 factures Métro à valider avant vendredi',  age: 'il y a 5 h' },
  { kind: 'warn', agent: 'Planning',      t: 'Le planning S+1 n\'est pas encore publié',   age: 'hier' },
  { kind: 'ok',   agent: 'TVA',           t: 'La TVA d\'avril est prête à exporter',        age: 'hier' },
];

const RECENT = [
  { who: 'Marc D.',   what: 'a clôturé le ticket Z',         when: 'il y a 12 min', a: 'MD', c: C.orangeDp },
  { who: 'Aline L.',  what: 'a saisi la facture Métro #4218', when: 'il y a 1 h',    a: 'AL', c: C.warn },
  { who: 'Bellia IA', what: 'a généré le rapport hebdo',     when: 'ce matin',      a: 'b',  c: C.orange },
  { who: 'Théo R.',   what: 'a publié le planning S+0',      when: 'hier 18:30',    a: 'TR', c: C.ok },
];

const DashboardScreen = ({ onNav }) => {
  const [period, setPeriod] = React.useState('mois');
  const todayCA = 4280;

  return (
    <PageShell current="dashboard" onNav={onNav}>
      <Header
        title="Bonjour Yannis"
        subtitle="lun. 11 mai 2026 — voici votre activité"
        right={<><PeriodPicker value={period} onChange={setPeriod} /><Btn kind="primary" icon={<Icon name="download" size={14} />}>Exporter</Btn></>}
      />

      {/* ====== HERO + 3 KPIs ====== */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.55fr 1fr', gap: 18, alignItems: 'stretch' }}>
        {/* Hero CA orange */}
        <div style={{
          background: `linear-gradient(135deg, ${C.orange} 0%, ${C.orangeDp} 100%)`,
          borderRadius: 26, padding: 28, color: C.cream, position: 'relative', overflow: 'hidden',
          minHeight: 280,
        }}>
          <div style={{ position: 'absolute', right: -140, top: -160, width: 380, height: 380, borderRadius: 999, background: 'rgba(255,248,238,0.10)' }} />
          <div style={{ position: 'absolute', right: -80, bottom: -200, width: 320, height: 320, borderRadius: 999, background: 'rgba(255,248,238,0.07)' }} />

          <div style={{ position: 'relative', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div>
              <div style={{ fontSize: 11, color: C.cream, opacity: 0.85, fontWeight: 600, letterSpacing: 0.8 }}>CA DU JOUR · TTC</div>
              <div style={{ fontSize: 58, fontWeight: 700, marginTop: 6, fontVariantNumeric: 'tabular-nums', letterSpacing: -1.5, lineHeight: 1 }}>
                {eur(todayCA)}
              </div>
              <div style={{ marginTop: 10, display: 'flex', alignItems: 'center', gap: 10 }}>
                <Pill kind="invert" icon={<Icon name="trendUp" size={11} />}>+12,3 % vs hier</Pill>
                <span style={{ fontSize: 12, opacity: 0.85 }}>147 tickets · panier moyen {eur(29.12, 2)}</span>
              </div>
            </div>
            <button style={{
              padding: '8px 14px', background: 'rgba(255,248,238,0.18)', border: '1px solid rgba(255,248,238,0.25)',
              borderRadius: 999, color: C.cream, fontSize: 11, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              Voir le détail <Icon name="arrowR" size={12} />
            </button>
          </div>

          {/* mini chart blanc */}
          <div style={{ position: 'relative', marginTop: 24, height: 130 }}>
            <svg viewBox="0 0 600 130" preserveAspectRatio="none" style={{ width: '100%', height: '100%' }}>
              <defs>
                <linearGradient id="hero-grad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#fff" stopOpacity="0.25" />
                  <stop offset="100%" stopColor="#fff" stopOpacity="0" />
                </linearGradient>
              </defs>
              {(() => {
                const data = SALES_30.slice(-14);
                const max = Math.max(...data) * 1.1;
                const pts = data.map((v, i) => [i * (600 / (data.length - 1)), 130 - (v / max) * 110]);
                const linePath = pts.map((p, i) => `${i === 0 ? 'M' : 'L'}${p[0].toFixed(1)},${p[1].toFixed(1)}`).join(' ');
                const areaPath = `${linePath} L600,130 L0,130 Z`;
                return (
                  <>
                    <path d={areaPath} fill="url(#hero-grad)" />
                    <path d={linePath} fill="none" stroke={C.cream} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
                    {pts.map((p, i) => (
                      <circle key={i} cx={p[0]} cy={p[1]} r={i === pts.length - 1 ? 5 : 0} fill={C.cream} />
                    ))}
                  </>
                );
              })()}
            </svg>
          </div>
        </div>

        {/* 3 KPI verticaux */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <KpiCard label="Marge brute" value={pct(68)} delta="+1,2 pt" deltaKind="ok" spark={SALES_30.map(v => v * 0.68)} sparkAccent={C.orange} />
          <KpiCard label="Masse salariale" value={pct(35)} delta="seuil 32 %" deltaKind="warn" alert progress={0.88} progressColor={C.warn} />
          <KpiCard label="Food cost" value={pct(32)} delta="+4 pts vs cible" deltaKind="err" alert progress={0.88} progressColor={C.err} />
        </div>
      </div>

      {/* ====== ROW 2 ====== */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.55fr 1fr', gap: 18, marginTop: 18 }}>
        <Card>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div>
              <div style={{ fontSize: 14, fontWeight: 700, color: C.ink }}>Chiffre d'affaires — 30 derniers jours</div>
              <div style={{ fontSize: 11, color: C.mute, marginTop: 4 }}>République · comparaison avec mai 2025</div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <Legend dot={C.orange} label="Mai 2026" />
              <Legend dot={C.mute2} label="Mai 2025" dashed />
            </div>
          </div>
          <div style={{ marginTop: 14 }}>
            <AreaLineChart data={SALES_30} prevData={SALES_30_PREV} height={260} />
          </div>
          <div style={{ display: 'flex', gap: 32, marginTop: 8, paddingTop: 14, borderTop: `1px solid ${C.lineSoft}` }}>
            <Stat label="Total mois" value={eur(MONTH_TOTAL)} delta="+8,1 %" />
            <Stat label="Jour moyen" value={eur(MONTH_TOTAL / 30)} delta="+5,2 %" />
            <Stat label="Meilleur jour" value="sam. 9 mai" delta={eur(5380)} deltaPlain />
            <Stat label="Objectif mois" value={eur(92000)} delta={pct((MONTH_TOTAL / 92000) * 100, 0) + ' atteint'} deltaPlain />
          </div>
        </Card>

        <Card style={{ padding: 0, display: 'flex', flexDirection: 'column' }}>
          <div style={{ padding: '22px 22px 14px', borderBottom: `1px solid ${C.lineSoft}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ width: 32, height: 32, borderRadius: 10, background: C.orangeWh, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name="sparkles" size={16} color={C.orangeDp} />
              </div>
              <div>
                <div style={{ fontSize: 13, fontWeight: 700, color: C.ink }}>Alertes des agents IA</div>
                <div style={{ fontSize: 10, color: C.mute }}>4 actions proactives</div>
              </div>
            </div>
            <Pill kind="accent">2 urgentes</Pill>
          </div>
          <div style={{ padding: 14, display: 'flex', flexDirection: 'column', gap: 8, flex: 1 }}>
            {ALERTS.map((a, i) => (
              <AlertRow key={i} {...a} />
            ))}
          </div>
          <div style={{ padding: '12px 22px', borderTop: `1px solid ${C.lineSoft}` }}>
            <button onClick={() => onNav('automation')} style={{
              background: 'transparent', border: 'none', color: C.orangeDp, fontWeight: 600, fontSize: 12,
              cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 4, fontFamily: 'inherit', padding: 0,
            }}>Voir tous les agents <Icon name="arrowR" size={13} /></button>
          </div>
        </Card>
      </div>

      {/* ====== ROW 3 — secondary metrics + activity ====== */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 18, marginTop: 18 }}>
        <Card>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 700, color: C.ink }}>Modes de vente</div>
              <div style={{ fontSize: 11, color: C.mute, marginTop: 2 }}>Mai 2026</div>
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 22, marginTop: 14 }}>
            <DonutChart slices={[
              { value: 65, color: C.orange },
              { value: 20, color: C.orangeDp },
              { value: 15, color: C.warn },
            ]} size={120} thickness={20} />
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, flex: 1 }}>
              {[
                { l: 'Sur place', v: '65 %', c: C.orange },
                { l: 'Click & collect', v: '20 %', c: C.orangeDp },
                { l: 'Livraison', v: '15 %', c: C.warn },
              ].map(s => (
                <div key={s.l} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ width: 8, height: 8, borderRadius: 999, background: s.c }} />
                  <span style={{ fontSize: 12, color: C.ink2, flex: 1 }}>{s.l}</span>
                  <span style={{ fontSize: 12, color: C.ink, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{s.v}</span>
                </div>
              ))}
            </div>
          </div>
        </Card>

        <Card>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 700, color: C.ink }}>Équipe en service</div>
              <div style={{ fontSize: 11, color: C.mute, marginTop: 2 }}>Aujourd'hui · 12 sur 18</div>
            </div>
            <Pill kind="ok">À jour</Pill>
          </div>
          <div style={{ marginTop: 18, display: 'flex', alignItems: 'center', gap: 18 }}>
            <div style={{ position: 'relative', width: 88, height: 88 }}>
              <DonutChart slices={[{ value: 12, color: C.orange }, { value: 6, color: C.lineSoft }]} size={88} thickness={14} />
              <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column' }}>
                <div style={{ fontSize: 18, fontWeight: 700, color: C.ink, lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>12</div>
                <div style={{ fontSize: 9, color: C.mute }}>/ 18</div>
              </div>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                {[
                  { i: 'MD', c: C.orange },
                  { i: 'AL', c: C.orangeDp },
                  { i: 'TR', c: C.warn },
                  { i: 'SN', c: C.ok },
                  { i: 'JB', c: C.mute },
                ].map((p, k) => (
                  <div key={p.i} style={{ marginLeft: k === 0 ? 0 : -8 }}>
                    <Avatar initials={p.i} size={30} c={p.c} style={{ border: `2px solid ${C.card}` }} />
                  </div>
                ))}
                <span style={{ marginLeft: 10, fontSize: 12, color: C.mute, fontWeight: 600 }}>+7 autres</span>
              </div>
              <div style={{ marginTop: 12, fontSize: 11, color: C.mute }}>
                <span style={{ color: C.ink2, fontWeight: 600 }}>Cuisine</span> 8 · <span style={{ color: C.ink2, fontWeight: 600 }}>Salle</span> 4
              </div>
            </div>
          </div>
        </Card>

        <Card style={{ padding: 0 }}>
          <div style={{ padding: '18px 22px 12px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: C.ink }}>Activité récente</div>
            <button style={{ background: 'transparent', border: 'none', cursor: 'pointer', padding: 0, color: C.mute, display: 'flex' }}>
              <Icon name="more" size={16} />
            </button>
          </div>
          <div style={{ padding: '0 12px 14px', display: 'flex', flexDirection: 'column', gap: 4 }}>
            {RECENT.map((r, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px', borderRadius: 12 }}>
                <Avatar initials={r.a} size={28} c={r.c} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12, color: C.ink2 }}>
                    <span style={{ color: C.ink, fontWeight: 600 }}>{r.who}</span> {r.what}
                  </div>
                  <div style={{ fontSize: 10, color: C.mute, marginTop: 1 }}>{r.when}</div>
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </PageShell>
  );
};

// ----- support components -----
const KpiCard = ({ label, value, delta, deltaKind = 'ok', spark, sparkAccent = C.orange, alert, progress, progressColor }) => (
  <div style={{
    flex: 1, background: C.card, border: `1px solid ${C.line}`, borderRadius: 22, padding: 20,
    display: 'flex', flexDirection: 'column', justifyContent: 'space-between', minHeight: 88,
  }}>
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
      <div>
        <div style={{ fontSize: 11, color: C.mute, fontWeight: 600, letterSpacing: 0.5 }}>{label.toUpperCase()}</div>
        <div style={{ fontSize: 28, fontWeight: 700, color: C.ink, marginTop: 6, fontVariantNumeric: 'tabular-nums', letterSpacing: -0.5, lineHeight: 1 }}>{value}</div>
      </div>
      <Pill kind={deltaKind} icon={alert ? <Icon name="alertT" size={11} /> : deltaKind === 'ok' ? <Icon name="trendUp" size={11} /> : null}>{delta}</Pill>
    </div>
    {spark && <div style={{ marginTop: 12, height: 32 }}><Sparkline data={spark} accent={sparkAccent} height={32} /></div>}
    {progress != null && (
      <div style={{ marginTop: 14 }}>
        <div style={{ height: 6, borderRadius: 999, background: C.lineSoft, overflow: 'hidden' }}>
          <div style={{ width: `${progress * 100}%`, height: '100%', background: progressColor, borderRadius: 999 }} />
        </div>
      </div>
    )}
  </div>
);

const AlertRow = ({ kind, agent, t, age }) => {
  const map = { err: { c: C.err, bg: C.errSft }, warn: { c: C.warn, bg: C.warnSft }, ok: { c: C.ok, bg: C.okSft } };
  const s = map[kind];
  return (
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '10px 12px', borderRadius: 14, background: C.cardWash }}>
      <div style={{ width: 28, height: 28, borderRadius: 9, background: s.bg, color: s.c, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <Icon name={kind === 'ok' ? 'checkC' : kind === 'err' ? 'alertT' : 'alertC'} size={14} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12, color: C.ink, fontWeight: 600, lineHeight: 1.4 }}>{t}</div>
        <div style={{ fontSize: 10, color: C.mute, marginTop: 3 }}>{age} · agent {agent}</div>
      </div>
      <button style={{ background: 'transparent', border: 'none', cursor: 'pointer', padding: 4, color: C.mute, display: 'flex' }}>
        <Icon name="chevRight" size={14} />
      </button>
    </div>
  );
};

const Legend = ({ dot, label, dashed }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
    {dashed
      ? <span style={{ width: 16, height: 2, borderTop: `2px dashed ${dot}` }} />
      : <span style={{ width: 8, height: 8, borderRadius: 999, background: dot }} />}
    <span style={{ fontSize: 10, color: C.mute, fontWeight: 600 }}>{label}</span>
  </div>
);

const Stat = ({ label, value, delta, deltaPlain }) => (
  <div>
    <div style={{ fontSize: 10, color: C.mute, fontWeight: 600, letterSpacing: 0.4 }}>{label.toUpperCase()}</div>
    <div style={{ fontSize: 16, fontWeight: 700, color: C.ink, marginTop: 4, fontVariantNumeric: 'tabular-nums' }}>{value}</div>
    <div style={{ fontSize: 10, color: deltaPlain ? C.mute : C.ok, marginTop: 2, fontWeight: 600 }}>{delta}</div>
  </div>
);

window.DashboardScreen = DashboardScreen;
