// Alternative views — Mijn dag, Per klant, Lijst, Team

const { useMemo: useMemoViews, useState: useStateViews } = React;

// ═══ MIJN DAG ═══════════════════════════════════════════
const MijnDag = ({ onPick }) => {
  const tasks = window.getMyTasks(window.CURRENT_USER_ID);
  const today = window.iso(window.today);
  const tomorrow = window.iso(window.addDays(window.today, 1));

  const groupBy = (pred) => tasks.filter(pred);
  const overdue = groupBy(t => window.daysUntil(t.deadline) < 0);
  const todayT  = groupBy(t => t.deadline === today);
  const tomor   = groupBy(t => t.deadline === tomorrow);
  const week    = groupBy(t => {
    const d = window.daysUntil(t.deadline);
    return d > 1 && d <= 7;
  });
  const later   = groupBy(t => window.daysUntil(t.deadline) > 7);

  const u = window.medewerkerById(window.CURRENT_USER_ID);

  return (
    <div style={{ flex: 1, overflowY: 'auto', background: 'var(--canvas)', padding: '22px 28px 40px' }}>
      <div style={{ maxWidth: 960, margin: '0 auto' }}>
        {/* Greeting banner */}
        <div style={{
          background: 'linear-gradient(135deg, oklch(0.96 0.03 60), oklch(0.97 0.02 40))',
          border: '1px solid oklch(0.88 0.04 60)',
          borderRadius: 12, padding: '18px 22px',
          display: 'flex', alignItems: 'center', gap: 16, marginBottom: 20,
        }}>
          <window.Avatar m={u} size={48} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 600, letterSpacing: 0.4 }}>ZATERDAG · 18 APRIL 2026</div>
            <div style={{ fontSize: 22, fontWeight: 650, letterSpacing: -0.4, marginTop: 2 }}>Goedemorgen, Sanne.</div>
            <div style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 4 }}>
              Je hebt <strong>{todayT.length} taken voor vandaag</strong>
              {overdue.length > 0 && <>, en <strong style={{ color: 'oklch(0.48 0.18 25)' }}>{overdue.length} stap{overdue.length>1?'pen':''} loopt te laat</strong></>}.
            </div>
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            <StatTile label="Vandaag" value={todayT.length} tone="hot" />
            <StatTile label="Deze week" value={week.length} />
            <StatTile label="Te laat" value={overdue.length} tone={overdue.length ? 'alert' : 'neutral'} />
          </div>
        </div>

        {overdue.length > 0 && (
          <TaskSection title="⚠ Te laat — vraagt nu aandacht" tone="alert" tasks={overdue} onPick={onPick} />
        )}
        <TaskSection title="Vandaag" tasks={todayT} onPick={onPick} defaultOpen />
        <TaskSection title="Morgen" tasks={tomor} onPick={onPick} defaultOpen />
        <TaskSection title="Deze week" tasks={week} onPick={onPick} />
        <TaskSection title="Later" tasks={later} onPick={onPick} />
      </div>
    </div>
  );
};

const StatTile = ({ label, value, tone }) => {
  const c = tone === 'hot' ? 'oklch(0.55 0.18 30)'
         : tone === 'alert' ? 'oklch(0.48 0.18 25)'
         : 'var(--ink-1)';
  return (
    <div style={{
      background: 'var(--paper)', border: '1px solid var(--line)',
      borderRadius: 9, padding: '8px 14px', minWidth: 70, textAlign: 'center',
    }}>
      <div style={{ fontSize: 10, color: 'var(--ink-3)', fontWeight: 600, letterSpacing: 0.4 }}>{label.toUpperCase()}</div>
      <div style={{ fontSize: 22, fontWeight: 650, color: c, letterSpacing: -0.5, marginTop: 2 }}>{value}</div>
    </div>
  );
};

const TaskSection = ({ title, tasks, onPick, tone, defaultOpen = true }) => {
  const [open, setOpen] = useStateViews(defaultOpen);
  if (tasks.length === 0) return null;
  return (
    <div style={{ marginBottom: 18 }}>
      <button onClick={() => setOpen(!open)} style={{
        display: 'flex', alignItems: 'center', gap: 8,
        padding: '6px 4px', background: 'transparent', border: 'none',
        cursor: 'pointer', color: tone === 'alert' ? 'oklch(0.45 0.18 25)' : 'var(--ink-1)',
        fontSize: 13, fontWeight: 650, letterSpacing: -0.1,
      }}>
        <span style={{ display: 'inline-block', transform: open ? 'rotate(90deg)' : 'none', transition: 'transform 120ms', color: 'var(--ink-3)' }}>
          <window.Icon name="chevron" size={12} />
        </span>
        {title}
        <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-3)', background: 'var(--surface-1)', padding: '1px 7px', borderRadius: 10 }}>{tasks.length}</span>
      </button>
      {open && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 6 }}>
          {tasks.map((t, i) => <TaskRow key={i} t={t} onPick={onPick} />)}
        </div>
      )}
    </div>
  );
};

const TaskRow = ({ t, onPick }) => {
  const p = window.PROJECTEN.find(x => x.id === t.projectId);
  const b = window.bucketById(t.bucketId);
  const klant = window.klantById(t.klant);
  const overdue = window.daysUntil(t.deadline) < 0;
  return (
    <div onClick={() => onPick(p)} style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '11px 14px', background: 'var(--paper)',
      border: '1px solid var(--line)', borderLeft: `3px solid ${overdue ? 'oklch(0.65 0.18 25)' : klant.kleur}`,
      borderRadius: 8, cursor: 'pointer',
    }}>
      <input type="checkbox" style={{ width: 16, height: 16, accentColor: 'oklch(0.58 0.12 150)' }} onClick={e => e.stopPropagation()} />
      <window.TeamChip team={b.team} compact />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-1)' }}>{b.naam}</div>
        <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2, display: 'flex', gap: 6, alignItems: 'center' }}>
          <span style={{ fontFamily: 'var(--mono)' }}>{t.projectId}</span>
          <span>·</span>
          <span>{t.projectNaam}</span>
          <span>·</span>
          <span style={{ color: klant.kleur, fontWeight: 600 }}>{klant.naam}</span>
        </div>
      </div>
      <window.PrioPill prio={t.prio} />
      <window.DeadlineChip deadline={t.deadline} />
    </div>
  );
};

// ═══ PER KLANT ═══════════════════════════════════════════
const PerKlant = ({ onPick }) => {
  const [expanded, setExpanded] = useStateViews(() => new Set(['hak','remia']));
  const grouped = useMemoViews(() => {
    const m = {};
    window.PROJECTEN.forEach(p => {
      if (p.huidigeBucket === 'afgerond' || p.huidigeBucket === 'niet-ok') return;
      (m[p.klant] = m[p.klant] || []).push(p);
    });
    return m;
  }, []);
  const klantIds = Object.keys(grouped).sort((a, b) => grouped[b].length - grouped[a].length);

  return (
    <div style={{ flex: 1, overflowY: 'auto', background: 'var(--canvas)', padding: '20px 28px 40px' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto' }}>
        {klantIds.map(kid => {
          const klant = window.klantById(kid);
          const projs = grouped[kid];
          const isOpen = expanded.has(kid);
          const toggle = () => {
            const s = new Set(expanded);
            s.has(kid) ? s.delete(kid) : s.add(kid);
            setExpanded(s);
          };
          const urgent = projs.filter(p => p.prio === 'dringend').length;
          return (
            <div key={kid} style={{
              background: 'var(--paper)', border: '1px solid var(--line)',
              borderRadius: 10, marginBottom: 12, overflow: 'hidden',
            }}>
              <button onClick={toggle} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                width: '100%', padding: '14px 18px', background: 'transparent',
                border: 'none', cursor: 'pointer', textAlign: 'left',
              }}>
                <div style={{
                  width: 36, height: 36, borderRadius: 9,
                  background: klant.kleur, color: 'white',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontWeight: 700, fontSize: 13, letterSpacing: -0.2,
                }}>{klant.naam.substring(0, 2).toUpperCase()}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 15, fontWeight: 650, color: 'var(--ink-1)', letterSpacing: -0.2 }}>{klant.naam}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>
                    {projs.length} lopende aanvragen · {projs.reduce((s, p) => s + p.sauzen.length, 0)} sauzen
                  </div>
                </div>
                {urgent > 0 && (
                  <window.Pill bg="oklch(0.94 0.06 25)" fg="oklch(0.45 0.18 25)">{urgent} dringend</window.Pill>
                )}
                <span style={{
                  color: 'var(--ink-3)',
                  transform: isOpen ? 'rotate(90deg)' : 'none',
                  transition: 'transform 140ms',
                }}>
                  <window.Icon name="chevron" size={16} />
                </span>
              </button>
              {isOpen && (
                <div style={{ padding: '0 18px 16px', borderTop: '1px solid var(--line)' }}>
                  <KlantProjectTable projs={projs} onPick={onPick} klantKleur={klant.kleur} />
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
};

const KlantProjectTable = ({ projs, onPick, klantKleur }) => {
  return (
    <div style={{ marginTop: 8 }}>
      {projs.map(p => (
        <div key={p.id} onClick={() => onPick(p)} style={{
          padding: '12px 4px', borderBottom: '1px solid var(--line)',
          cursor: 'pointer', display: 'flex', flexDirection: 'column', gap: 8,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ fontSize: 11, fontFamily: 'var(--mono)', color: 'var(--ink-3)', fontWeight: 600 }}>{p.id}</span>
            <span style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink-1)' }}>{p.naam}</span>
            <span style={{ flex: 1 }} />
            <window.PrioPill prio={p.prio} />
            <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>deadline {window.fmtDate(p.einde)}</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(230px, 1fr))', gap: 6 }}>
            {p.sauzen.map((s, i) => {
              const b = window.bucketById(s.bucketId);
              const prog = window.sausProgress(p, s.bucketId);
              return (
                <div key={i} style={{
                  padding: '7px 10px', border: '1px solid var(--line)', borderRadius: 6,
                  background: 'var(--surface-1)',
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                    <span style={{ fontSize: 11.5, fontWeight: 550, color: 'var(--ink-1)', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.naam}</span>
                    <window.TeamChip team={b.team} compact />
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <div style={{ flex: 1, height: 3, background: 'var(--surface-2)', borderRadius: 2, overflow: 'hidden' }}>
                      <div style={{ height: '100%', width: `${Math.max(prog*100,4)}%`, background: klantKleur }} />
                    </div>
                    <span style={{ fontSize: 10, color: 'var(--ink-3)', fontFamily: 'var(--mono)' }}>{b.naam}</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      ))}
    </div>
  );
};

// ═══ LIJST ══════════════════════════════════════════════
const Lijst = ({ onPick }) => {
  const [sort, setSort] = useStateViews('deadline');
  const projs = useMemoViews(() => {
    const arr = [...window.PROJECTEN];
    arr.sort((a, b) => {
      if (sort === 'deadline') return a.einde.localeCompare(b.einde);
      if (sort === 'klant') return window.klantById(a.klant).naam.localeCompare(window.klantById(b.klant).naam);
      if (sort === 'prio') {
        const order = { dringend: 0, belangrijk: 1, gemiddeld: 2, laag: 3 };
        return order[a.prio] - order[b.prio];
      }
      return 0;
    });
    return arr;
  }, [sort]);

  return (
    <div style={{ flex: 1, overflow: 'auto', background: 'var(--canvas)', padding: '18px 28px 40px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12, fontSize: 12, color: 'var(--ink-3)' }}>
        Sorteer:
        {['deadline','klant','prio'].map(s => (
          <button key={s} onClick={() => setSort(s)} style={{
            padding: '3px 8px', fontSize: 11.5, fontWeight: 600, cursor: 'pointer',
            background: sort === s ? 'var(--ink-1)' : 'transparent',
            color: sort === s ? 'var(--paper)' : 'var(--ink-2)',
            border: sort === s ? 'none' : '1px solid var(--line)', borderRadius: 5,
          }}>{s}</button>
        ))}
      </div>
      <div style={{ background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 10, overflow: 'hidden' }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: '98px 1.6fr 1fr 180px 110px 90px 120px',
          padding: '10px 16px', fontSize: 10.5, fontWeight: 650,
          color: 'var(--ink-3)', letterSpacing: 0.5, background: 'var(--surface-1)',
          borderBottom: '1px solid var(--line)',
        }}>
          <span>PROJECT ID</span>
          <span>NAAM</span>
          <span>KLANT</span>
          <span>HUIDIGE STAP</span>
          <span>PRIO</span>
          <span>TEAM</span>
          <span>DEADLINE</span>
        </div>
        {projs.map(p => {
          const klant = window.klantById(p.klant);
          const b = window.bucketById(p.huidigeBucket);
          return (
            <div key={p.id} onClick={() => onPick(p)} style={{
              display: 'grid',
              gridTemplateColumns: '98px 1.6fr 1fr 180px 110px 90px 120px',
              padding: '10px 16px', fontSize: 12.5,
              borderBottom: '1px solid var(--line)', cursor: 'pointer',
              alignItems: 'center',
            }}
            onMouseEnter={e => e.currentTarget.style.background = 'var(--surface-1)'}
            onMouseLeave={e => e.currentTarget.style.background = 'var(--paper)'}
            >
              <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-2)', fontWeight: 550 }}>{p.id}</span>
              <span style={{ fontWeight: 600, color: 'var(--ink-1)' }}>{p.naam}</span>
              <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: klant.kleur }} />
                {klant.naam}
              </span>
              <span><window.TeamChip team={b.team} compact /> <span style={{ fontSize: 11.5, color: 'var(--ink-2)', marginLeft: 3 }}>{b.naam}</span></span>
              <span><window.PrioPill prio={p.prio} /></span>
              <span><window.AvatarStack ids={p.toegewezen} size={20} max={3} /></span>
              <span style={{ fontSize: 11.5 }}><window.DeadlineChip deadline={p.einde} /></span>
            </div>
          );
        })}
      </div>
    </div>
  );
};

// ═══ TEAM WORKLOAD ══════════════════════════════════════
const Team = ({ onPick }) => {
  const workload = useMemoViews(() => {
    const m = {};
    window.MEDEWERKERS.forEach(med => m[med.id] = { open: 0, overdue: 0, deze_week: 0, vandaag: 0 });
    window.PROJECTEN.forEach(p => {
      Object.entries(p.plan).forEach(([bid, step]) => {
        if (step.done || !step.owner) return;
        const d = window.daysUntil(step.deadline);
        const bucket = m[step.owner];
        if (!bucket) return;
        bucket.open++;
        if (d < 0) bucket.overdue++;
        if (d === 0) bucket.vandaag++;
        if (d >= 0 && d <= 7) bucket.deze_week++;
      });
    });
    return m;
  }, []);

  const maxOpen = Math.max(...Object.values(workload).map(w => w.open), 1);

  return (
    <div style={{ flex: 1, overflowY: 'auto', background: 'var(--canvas)', padding: '22px 28px 40px' }}>
      <div style={{ maxWidth: 1100, margin: '0 auto' }}>
        <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 14, lineHeight: 1.5 }}>
          Openstaande stappen per medewerker, gesorteerd op bezetting. Rode balk = te laat.
        </div>
        <div style={{ background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 10, padding: 18 }}>
          {window.MEDEWERKERS
            .map(m => ({ m, w: workload[m.id] }))
            .sort((a, b) => b.w.open - a.w.open)
            .map(({ m, w }) => (
              <div key={m.id} style={{
                display: 'grid', gridTemplateColumns: '200px 1fr 80px 90px 90px',
                alignItems: 'center', padding: '10px 0',
                borderBottom: '1px solid var(--line)', gap: 12,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <window.Avatar m={m} size={30} />
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-1)' }}>{m.naam}</div>
                    <div style={{ fontSize: 10, color: 'var(--ink-3)' }}><window.TeamChip team={m.rol} compact /></div>
                  </div>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                  <div style={{ display: 'flex', height: 18, borderRadius: 4, overflow: 'hidden', background: 'var(--surface-2)' }}>
                    {w.overdue > 0 && (
                      <div style={{ width: `${w.overdue/maxOpen*100}%`, background: 'oklch(0.60 0.18 25)' }} />
                    )}
                    {w.vandaag > 0 && (
                      <div style={{ width: `${w.vandaag/maxOpen*100}%`, background: 'oklch(0.68 0.15 55)' }} />
                    )}
                    {Math.max(w.open - w.overdue - w.vandaag, 0) > 0 && (
                      <div style={{ width: `${Math.max(w.open - w.overdue - w.vandaag, 0)/maxOpen*100}%`, background: m.kleur, opacity: 0.5 }} />
                    )}
                  </div>
                </div>
                <div style={{ textAlign: 'center' }}>
                  <div style={{ fontSize: 17, fontWeight: 650, color: 'var(--ink-1)', letterSpacing: -0.3 }}>{w.open}</div>
                  <div style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: 0.3 }}>OPEN</div>
                </div>
                <div style={{ textAlign: 'center' }}>
                  <div style={{ fontSize: 17, fontWeight: 650, color: w.overdue ? 'oklch(0.48 0.18 25)' : 'var(--ink-3)', letterSpacing: -0.3 }}>{w.overdue}</div>
                  <div style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: 0.3 }}>TE LAAT</div>
                </div>
                <div style={{ textAlign: 'center' }}>
                  <div style={{ fontSize: 17, fontWeight: 650, color: 'var(--ink-1)', letterSpacing: -0.3 }}>{w.deze_week}</div>
                  <div style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: 0.3 }}>DEZE WEEK</div>
                </div>
              </div>
            ))}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { MijnDag, PerKlant, Lijst, Team });
