/* global React, MEMBERS, TESTS, SCORES, PROGRAMS, SCHEDULE, LOGS, DAY_TYPES,
   TODAY, PERIOD_START, PERIOD_WEEKS,
   Eyebrow, Avatar, Card, Pill, DayBadge, Progress, Stat, SectionHeader,
   Segmented, Tick, Sparkline, Button, Input,
   improvement, addDays, dKey, getDayType, getLog, fmtDate, weekNumber */
const { useState, useMemo } = React;

function Dashboard({ memberId, setRoute, tweaks, programs }) {
  const member = MEMBERS.find(m => m.id === memberId);
  const memberScores = SCORES[memberId] || {};
  const todayKey = dKey(TODAY);
  const todayType = getDayType(memberId, TODAY);
  const todayLog = getLog(memberId, TODAY);
  const program = programs[todayType];

  // Compute completion across past 14 days (or week)
  const range = tweaks.range === 'month' ? 28 : 14;
  let ja = 0, delvis = 0, nej = 0, total = 0;
  for (let i = 0; i < range; i++) {
    const d = addDays(TODAY, -i);
    if (d < PERIOD_START) continue;
    total++;
    const log = getLog(memberId, d);
    if (!log) { nej++; continue; }
    if (log.done === 'ja') ja++;
    else if (log.done === 'delvis') delvis++;
    else nej++;
  }
  const completionPct = total ? Math.round(((ja + delvis * 0.5) / total) * 100) : 0;

  // Streak — consecutive days with log.done === 'ja'
  let streak = 0;
  for (let i = 0; i < 60; i++) {
    const d = addDays(TODAY, -i);
    if (d < PERIOD_START) break;
    const l = getLog(memberId, d);
    if (l && l.done === 'ja') streak++;
    else if (i > 0) break; // allow today to not be logged
  }

  // Top improvement test
  const tests = TESTS.filter(t => memberScores[t.id]);
  const improvements = tests.map(t => {
    const s = memberScores[t.id];
    const imp = improvement(s.b, s.m, t.dir);
    return { test: t, imp };
  }).filter(x => x.imp).sort((a, b) => b.imp.pct - a.imp.pct);
  const topImp = improvements[0];

  return (
    <div style={{ padding: '32px 32px 80px', maxWidth: 1280, margin: '0 auto' }}>
      {/* Hero header */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 32 }}>
        <div>
          <Eyebrow style={{ marginBottom: 12 }}>{fmtDate(TODAY)} · Vecka {weekNumber(TODAY)} av {PERIOD_WEEKS}</Eyebrow>
          <h1 style={{ margin: 0, fontFamily: 'var(--font-sans)', fontSize: 44, fontWeight: 500, letterSpacing: '-0.025em', lineHeight: 1.05 }}>
            God morgon, <span style={{ color: member.color }}>{member.name}</span>.
          </h1>
          <p style={{ margin: '12px 0 0', maxWidth: 560, fontSize: 15, color: 'var(--fg-muted)', lineHeight: 1.55 }}>
            {member.goal}
          </p>
        </div>
        <Avatar member={member} size={88} />
      </div>

      {/* KPI strip */}
      <Card pad={0} style={{ marginBottom: 24 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)' }}>
          <div style={{ padding: '20px 24px', borderRight: '1px solid var(--border)' }}>
            <Stat
              label="Genomförande"
              value={completionPct}
              unit="%"
              sub={`${ja} ja · ${delvis} delvis · ${nej} miss`}
            />
            <div style={{ marginTop: 10 }}>
              <Progress value={completionPct} color="var(--signal)" />
            </div>
          </div>
          <div style={{ padding: '20px 24px', borderRight: '1px solid var(--border)' }}>
            <Stat
              label="Streak"
              value={streak}
              unit="dagar"
              sub={streak > 0 ? 'sammanhängande träning' : 'starta idag'}
            />
          </div>
          <div style={{ padding: '20px 24px', borderRight: '1px solid var(--border)' }}>
            <Stat
              label="Veckor kvar"
              value={Math.max(0, PERIOD_WEEKS - weekNumber(TODAY) + 1)}
              unit="v"
              sub={`till post-test`}
            />
          </div>
          <div style={{ padding: '20px 24px' }}>
            {topImp ? (
              <Stat
                label="Bästa förbättring"
                value={`${topImp.imp.pct > 0 ? '+' : ''}${topImp.imp.pct.toFixed(1)}`}
                unit="%"
                sub={topImp.test.name}
                deltaPct={topImp.imp.pct}
                dir={topImp.test.dir}
              />
            ) : (
              <Stat label="Bästa förbättring" value="—" sub="kör baseline-tester först" />
            )}
          </div>
        </div>
      </Card>

      {/* Two-column body */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 24 }}>
        {/* LEFT: Today's plan */}
        <Card pad={0}>
          <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <Eyebrow>Idag · {fmtDate(TODAY)}</Eyebrow>
              <h3 style={{ margin: '6px 0 0', fontSize: 22, fontWeight: 500, letterSpacing: '-0.015em', display: 'flex', alignItems: 'center', gap: 12 }}>
                Dagens pass
                <DayBadge type={todayType} />
              </h3>
            </div>
            <Button kind="primary" size="sm" onClick={() => setRoute('logg')}>
              Logga dagen
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6" /></svg>
            </Button>
          </div>
          <div>
            {[
              { key: 'sn', dataKey: 'snabbhet',  label: 'Snabbhet',  done: todayLog?.sn },
              { key: 'st', dataKey: 'styrka',    label: 'Styrka',    done: todayLog?.st },
              { key: 'ko', dataKey: 'kondition', label: 'Kondition', done: todayLog?.ko },
              { key: 'ro', dataKey: 'rorlighet', label: 'Rörlighet', done: todayLog?.ro },
            ].map((b, i, arr) => {
              const blk = program[b.dataKey];
              return (
                <div key={b.key} style={{
                  padding: '16px 24px',
                  borderBottom: i < arr.length - 1 ? '1px solid var(--border-faint)' : 'none',
                  display: 'flex', gap: 16, alignItems: 'flex-start',
                }}>
                  <div style={{
                    width: 22, height: 22, marginTop: 2, flexShrink: 0,
                    borderRadius: 4,
                    border: `1.5px solid ${b.done ? 'var(--signal)' : 'var(--border-strong)'}`,
                    background: b.done ? 'var(--signal)' : 'transparent',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    {b.done && <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12" /></svg>}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <Eyebrow style={{ marginBottom: 4 }}>{b.label}</Eyebrow>
                    {blk.intro && <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginBottom: 6, fontStyle: 'italic' }}>{blk.intro}</div>}
                    <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 3 }}>
                      {blk.exercises.map(e => (
                        <li key={e.id} style={{ fontSize: 13, color: 'var(--fg)', lineHeight: 1.45 }}>
                          • {window.exerciseLine(e)}
                        </li>
                      ))}
                    </ul>
                  </div>
                </div>
              );
            })}
          </div>
        </Card>

        {/* RIGHT column */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
          {/* Family overview */}
          <Card pad={0}>
            <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div>
                <Eyebrow>Familjen idag</Eyebrow>
                <h3 style={{ margin: '4px 0 0', fontSize: 16, fontWeight: 500 }}>Vad gör alla?</h3>
              </div>
            </div>
            <div>
              {MEMBERS.map((m, i) => {
                const t = getDayType(m.id, TODAY);
                const l = getLog(m.id, TODAY);
                const done = l?.done === 'ja';
                return (
                  <div key={m.id} style={{
                    padding: '12px 20px',
                    borderBottom: i < MEMBERS.length - 1 ? '1px solid var(--border-faint)' : 'none',
                    display: 'flex', alignItems: 'center', gap: 12,
                  }}>
                    <Avatar member={m} size={32} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--fg)' }}>{m.name}</div>
                      <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--fg-subtle)', letterSpacing: '0.04em', textTransform: 'uppercase' }}>{m.role}</div>
                    </div>
                    <DayBadge type={t} />
                    <div style={{
                      width: 8, height: 8, borderRadius: 999,
                      background: done ? 'var(--success)' : (l?.done === 'delvis' ? 'var(--warning)' : 'var(--ink-150)'),
                    }} title={l?.done || 'ej loggad'} />
                  </div>
                );
              })}
            </div>
          </Card>

          {/* Top improvements */}
          <Card pad={0}>
            <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--border)' }}>
              <Eyebrow>Tester · baseline → senaste</Eyebrow>
              <h3 style={{ margin: '4px 0 0', fontSize: 16, fontWeight: 500 }}>Förbättring</h3>
            </div>
            {improvements.length === 0 ? (
              <div style={{ padding: 24, textAlign: 'center', color: 'var(--fg-subtle)', fontSize: 13 }}>
                Inga tester loggade än.<br />
                <button onClick={() => setRoute('tester')} style={{ marginTop: 8, fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--signal)', background: 'none', border: 'none', cursor: 'pointer', borderBottom: '1px solid currentColor', padding: 0 }}>
                  Lägg till baseline
                </button>
              </div>
            ) : improvements.slice(0, 5).map((x, i, arr) => {
              const s = memberScores[x.test.id];
              const good = x.test.dir === 'lower' ? x.imp.pct < 0 : x.imp.pct > 0;
              return (
                <div key={x.test.id} style={{
                  padding: '12px 20px',
                  borderBottom: i < arr.length - 1 ? '1px solid var(--border-faint)' : 'none',
                  display: 'grid', gridTemplateColumns: '1fr auto', gap: 12, alignItems: 'center',
                }}>
                  <div>
                    <div style={{ fontSize: 13, color: 'var(--fg)', fontWeight: 500 }}>{x.test.name}</div>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-subtle)', marginTop: 2, fontVariantNumeric: 'tabular-nums' }}>
                      {s.b} → {s.m} {x.test.unit}
                    </div>
                  </div>
                  <div style={{
                    fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 500,
                    fontVariantNumeric: 'tabular-nums',
                    color: good ? 'var(--success)' : 'var(--danger)',
                  }}>
                    {x.imp.pct > 0 ? '+' : ''}{x.imp.pct.toFixed(1)}%
                  </div>
                </div>
              );
            })}
            <div style={{ padding: '10px 20px', borderTop: '1px solid var(--border-faint)' }}>
              <button onClick={() => setRoute('tester')} style={{ fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--fg-muted)', background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>
                Visa alla tester →
              </button>
            </div>
          </Card>
        </div>
      </div>

      {/* Week strip */}
      <div style={{ marginTop: 32 }}>
        <SectionHeader eyebrow="Vecka i översikt" title="Senaste 14 dagarna" />
        <Card pad={20}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(14, 1fr)', gap: 4 }}>
            {Array.from({ length: 14 }, (_, i) => {
              const d = addDays(TODAY, -(13 - i));
              const t = getDayType(memberId, d);
              const l = getLog(memberId, d);
              const dt = DAY_TYPES.find(x => x.id === t);
              const isToday = dKey(d) === todayKey;
              return (
                <div key={i} style={{
                  display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
                  padding: '6px 0',
                  border: isToday ? '1px solid var(--signal)' : '1px solid transparent',
                  borderRadius: 4, background: isToday ? 'var(--signal-tint)' : 'transparent',
                }}>
                  <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--fg-subtle)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>
                    {['sön','mån','tis','ons','tor','fre','lör'][d.getDay()]}
                  </div>
                  <div style={{ fontFamily: 'var(--font-mono)', fontSize: 13, fontVariantNumeric: 'tabular-nums', fontWeight: 500, color: 'var(--fg)' }}>
                    {d.getDate()}
                  </div>
                  <div style={{ width: 8, height: 8, borderRadius: 999, background: dt?.dot || 'var(--ink-150)' }} />
                  <div style={{
                    width: 6, height: 6, borderRadius: 999,
                    background: l?.done === 'ja' ? 'var(--success)' : l?.done === 'delvis' ? 'var(--warning)' : 'transparent',
                  }} />
                </div>
              );
            })}
          </div>
        </Card>
      </div>
    </div>
  );
}

window.Dashboard = Dashboard;
