// Kanban view — the main overview

const { useState, useMemo, useRef, useEffect } = React;

const FASE_GROEPEN = [
  { id: 'aanvraag',    label: 'Aanvraag' },
  { id: 'ontwikkeling',label: 'Ontwikkeling' },
  { id: 'specificatie',label: 'Specificatie' },
  { id: 'calculatie',  label: 'Calculatie' },
  { id: 'commercie',   label: 'Commercie' },
  { id: 'productie',   label: 'Productie' },
  { id: 'klaar',       label: 'Klaar' },
  { id: 'wachten',     label: 'Wachtkamer' },
];

const KanbanCard = ({ p, onClick, density }) => {
  const klant = window.klantById(p.klant);
  const bucket = window.bucketById(p.huidigeBucket);
  const step = p.plan[p.huidigeBucket];
  const overdue = step && !step.done && window.daysUntil(step.deadline) < 0;
  const isCompact = density === 'compact';

  const sauzenOpKaart = p.sauzen.slice(0, 4);

  return (
    <div onClick={onClick} style={{
      background: 'var(--paper)',
      border: '1px solid var(--line)',
      borderTop: `3px solid ${klant.kleur}`,
      borderRadius: 8,
      padding: isCompact ? '10px 11px' : '12px 13px',
      cursor: 'pointer',
      boxShadow: overdue ? '0 0 0 1px oklch(0.75 0.15 25 / 0.5), 0 1px 2px rgba(0,0,0,0.03)' : '0 1px 2px rgba(0,0,0,0.03)',
      marginBottom: 8,
      transition: 'transform 120ms, box-shadow 120ms',
    }}
    onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-1px)'; e.currentTarget.style.boxShadow = '0 2px 6px rgba(0,0,0,0.06)'; }}
    onMouseLeave={e => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = overdue ? '0 0 0 1px oklch(0.75 0.15 25 / 0.5), 0 1px 2px rgba(0,0,0,0.03)' : '0 1px 2px rgba(0,0,0,0.03)'; }}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
        <span style={{ fontSize: 10, fontFamily: 'var(--mono)', color: 'var(--ink-3)', fontWeight: 600, letterSpacing: 0.3 }}>{p.id}</span>
        <span style={{ flex: 1 }} />
        {p.prio === 'dringend' && <window.Icon name="alert" size={12} />}
        <window.PrioPill prio={p.prio} />
      </div>
      <div style={{ fontSize: 13.5, fontWeight: 600, lineHeight: 1.25, marginBottom: 3, color: 'var(--ink-1)' }}>{p.naam}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginBottom: 10 }}>
        <span style={{ width: 6, height: 6, borderRadius: '50%', background: klant.kleur }} />
        <span style={{ fontSize: 11.5, color: 'var(--ink-2)', fontWeight: 500 }}>{klant.naam}</span>
      </div>

      {/* Sauzen mini-voortgang */}
      {!isCompact && p.sauzen.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4, marginBottom: 10 }}>
          {sauzenOpKaart.map((s, i) => {
            const prog = window.sausProgress(p, s.bucketId);
            const isHold = prog === -1;
            const inThisBucket = s.bucketId === p.huidigeBucket;
            return (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
                  <span style={{
                    width: 5, height: 5, borderRadius: '50%',
                    background: inThisBucket ? klant.kleur : 'var(--ink-3)',
                    opacity: inThisBucket ? 1 : 0.4, flexShrink: 0,
                  }} />
                  <span style={{ fontSize: 11, color: 'var(--ink-2)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.naam}</span>
                </div>
                <div style={{ width: 48, height: 3, background: 'var(--surface-2)', borderRadius: 2, overflow: 'hidden', flexShrink: 0 }}>
                  <div style={{
                    height: '100%',
                    width: isHold ? '100%' : `${Math.max(prog * 100, 6)}%`,
                    background: isHold ? 'oklch(0.75 0.04 80)' : klant.kleur,
                  }} />
                </div>
              </div>
            );
          })}
          {p.sauzen.length > 4 && (
            <div style={{ fontSize: 10.5, color: 'var(--ink-3)', marginLeft: 11 }}>+ {p.sauzen.length - 4} meer</div>
          )}
        </div>
      )}

      {/* Footer */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <window.AvatarStack ids={p.toegewezen} size={20} max={3} />
        <span style={{ flex: 1 }} />
        {p.opmerkingen > 0 && (
          <span style={{ display: 'flex', alignItems: 'center', gap: 2, fontSize: 10.5, color: 'var(--ink-3)' }}>
            <window.Icon name="chat" size={11} /> {p.opmerkingen}
          </span>
        )}
        {p.bijlagen > 0 && (
          <span style={{ display: 'flex', alignItems: 'center', gap: 2, fontSize: 10.5, color: 'var(--ink-3)' }}>
            <window.Icon name="attach" size={11} /> {p.bijlagen}
          </span>
        )}
        {step && !step.done && (
          <window.DeadlineChip deadline={step.deadline} done={step.done} />
        )}
      </div>
    </div>
  );
};

const KanbanColumn = ({ bucket, projecten, onPick, density }) => {
  const color = window.TEAM_COLORS[bucket.team] || window.TEAM_COLORS['—'];
  const count = projecten.length;
  return (
    <div style={{
      width: 268, flexShrink: 0,
      display: 'flex', flexDirection: 'column',
      background: 'var(--surface-1)', borderRadius: 10,
      padding: 10, maxHeight: '100%',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '2px 4px 10px' }}>
        <window.TeamChip team={bucket.team} compact />
        <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink-1)', flex: 1, lineHeight: 1.2 }}>{bucket.naam}</span>
        <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-3)', background: 'var(--paper)', padding: '1px 6px', borderRadius: 10 }}>{count}</span>
      </div>
      <div style={{ overflowY: 'auto', flex: 1, paddingRight: 2 }}>
        {projecten.map(p => (
          <KanbanCard key={p.id} p={p} onClick={() => onPick(p)} density={density} />
        ))}
        {count === 0 && (
          <div style={{
            padding: '16px 10px', textAlign: 'center', fontSize: 11.5,
            color: 'var(--ink-3)', border: '1px dashed var(--line)', borderRadius: 6,
          }}>—</div>
        )}
      </div>
    </div>
  );
};

const Kanban = ({ onPick, density, search }) => {
  const [activeFase, setActiveFase] = useState('all');
  const projects = window.PROJECTEN;
  const buckets = window.BUCKETS;

  const filteredProjecten = useMemo(() => {
    const s = search.toLowerCase();
    if (!s) return projects;
    return projects.filter(p =>
      p.naam.toLowerCase().includes(s) ||
      p.id.toLowerCase().includes(s) ||
      window.klantById(p.klant).naam.toLowerCase().includes(s) ||
      p.sauzen.some(sa => sa.naam.toLowerCase().includes(s))
    );
  }, [search, projects]);

  const byBucket = useMemo(() => {
    const m = {};
    buckets.forEach(b => m[b.id] = []);
    filteredProjecten.forEach(p => {
      (m[p.huidigeBucket] = m[p.huidigeBucket] || []).push(p);
    });
    return m;
  }, [filteredProjecten, buckets]);

  const faseCounts = useMemo(() => {
    const m = { all: filteredProjecten.length };
    FASE_GROEPEN.forEach(f => {
      m[f.id] = buckets.filter(b => b.fase === f.id).reduce((sum, b) => sum + (byBucket[b.id]?.length || 0), 0);
    });
    return m;
  }, [byBucket, filteredProjecten, buckets]);

  const visibleBuckets = activeFase === 'all'
    ? buckets
    : buckets.filter(b => b.fase === activeFase);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0 }}>
      {/* Fase tabs */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 4,
        padding: '10px 24px', background: 'var(--paper)',
        borderBottom: '1px solid var(--line)',
        overflowX: 'auto',
      }}>
        <button onClick={() => setActiveFase('all')} className={activeFase === 'all' ? 'tab-on' : 'tab'}>
          Alle fases <span className="tab-count">{faseCounts.all}</span>
        </button>
        <div style={{ width: 1, height: 18, background: 'var(--line)', margin: '0 6px' }} />
        {FASE_GROEPEN.map(f => (
          <button key={f.id} onClick={() => setActiveFase(f.id)} className={activeFase === f.id ? 'tab-on' : 'tab'}>
            {f.label} <span className="tab-count">{faseCounts[f.id]}</span>
          </button>
        ))}
      </div>

      {/* Columns */}
      <div style={{
        flex: 1, overflowX: 'auto', overflowY: 'hidden',
        padding: '14px 24px 20px', display: 'flex', gap: 10,
        background: 'var(--canvas)',
      }}>
        {visibleBuckets.map(b => (
          <KanbanColumn key={b.id} bucket={b} projecten={byBucket[b.id] || []} onPick={onPick} density={density} />
        ))}
      </div>
    </div>
  );
};

window.Kanban = Kanban;
