// Project detail slide-over panel

const { useState: useStateDetail } = React;

const ProjectDetail = ({ p, onClose }) => {
  const [tab, setTab] = useStateDetail('plan');
  if (!p) return null;
  const klant = window.klantById(p.klant);
  const bucket = window.bucketById(p.huidigeBucket);
  const teamC = window.TEAM_COLORS[bucket.team];

  const steps = window.BUCKETS
    .filter(b => p.plan[b.id])
    .map(b => ({ ...b, ...p.plan[b.id] }));

  const done = steps.filter(s => s.done).length;
  const total = steps.length || 1;

  return (
    <>
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, background: 'rgba(20,14,10,0.28)',
        zIndex: 40, animation: 'fadeIn 180ms ease-out',
      }} />
      <aside style={{
        position: 'fixed', top: 0, right: 0, bottom: 0, width: 560,
        background: 'var(--paper)', zIndex: 41,
        boxShadow: '-8px 0 30px rgba(0,0,0,0.12)',
        display: 'flex', flexDirection: 'column',
        animation: 'slideIn 220ms ease-out',
      }}>
        {/* Header */}
        <div style={{
          padding: '18px 22px 14px', borderBottom: '1px solid var(--line)',
          borderTop: `3px solid ${klant.kleur}`,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
            <span style={{ fontSize: 11, fontFamily: 'var(--mono)', fontWeight: 600, color: 'var(--ink-3)', letterSpacing: 0.3 }}>{p.id}</span>
            <span style={{ width: 3, height: 3, borderRadius: '50%', background: 'var(--ink-3)' }} />
            <span style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 12, color: 'var(--ink-2)' }}>
              <span style={{ width: 7, height: 7, borderRadius: '50%', background: klant.kleur }} />
              {klant.naam}
            </span>
            <span style={{ flex: 1 }} />
            <window.PrioPill prio={p.prio} />
            <button onClick={onClose} style={{
              width: 28, height: 28, border: 'none', background: 'transparent',
              borderRadius: 6, cursor: 'pointer', color: 'var(--ink-3)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}><window.Icon name="x" size={16} /></button>
          </div>
          <h2 style={{ fontSize: 21, fontWeight: 650, letterSpacing: -0.4, margin: 0, lineHeight: 1.2 }}>{p.naam}</h2>

          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 12, fontSize: 12 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <window.TeamChip team={bucket.team} compact />
              <span style={{ color: 'var(--ink-2)', fontWeight: 500 }}>{bucket.naam}</span>
            </div>
            <span style={{ width: 1, height: 14, background: 'var(--line)' }} />
            <span style={{ color: 'var(--ink-3)' }}>Opgevolgd door</span>
            <window.AvatarStack ids={p.toegewezen} size={22} />
          </div>

          <div style={{ marginTop: 14, display: 'flex', gap: 18 }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 10, color: 'var(--ink-3)', fontWeight: 600, letterSpacing: 0.4 }}>VOORTGANG</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6 }}>
                <div style={{ flex: 1, height: 6, background: 'var(--surface-2)', borderRadius: 3, overflow: 'hidden' }}>
                  <div style={{ height: '100%', width: `${done/total*100}%`, background: klant.kleur }} />
                </div>
                <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-2)' }}>{done}/{total}</span>
              </div>
            </div>
            <div style={{ minWidth: 90 }}>
              <div style={{ fontSize: 10, color: 'var(--ink-3)', fontWeight: 600, letterSpacing: 0.4 }}>DEADLINE</div>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-1)', marginTop: 3 }}>{window.fmtDateLong(p.einde)}</div>
            </div>
          </div>
        </div>

        {/* Tabs */}
        <div style={{ display: 'flex', gap: 2, padding: '0 14px', borderBottom: '1px solid var(--line)' }}>
          {[
            { id: 'plan', label: 'Planning per stap', count: steps.length },
            { id: 'sauzen', label: 'Sauzen', count: p.sauzen.length },
            { id: 'chat', label: 'Opmerkingen', count: p.opmerkingen },
            { id: 'files', label: 'Bijlagen', count: p.bijlagen },
          ].map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              padding: '10px 12px', border: 'none', background: 'transparent',
              fontSize: 12.5, fontWeight: 550, cursor: 'pointer',
              color: tab === t.id ? 'var(--ink-1)' : 'var(--ink-3)',
              borderBottom: tab === t.id ? '2px solid var(--ink-1)' : '2px solid transparent',
              marginBottom: -1,
            }}>
              {t.label} <span style={{ color: 'var(--ink-3)', marginLeft: 3 }}>{t.count}</span>
            </button>
          ))}
        </div>

        {/* Content */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '18px 22px' }}>
          {tab === 'plan' && <PlanPerStap p={p} steps={steps} />}
          {tab === 'sauzen' && <SauzenTab p={p} />}
          {tab === 'chat' && <ChatTab p={p} />}
          {tab === 'files' && <FilesTab p={p} />}
        </div>
      </aside>
    </>
  );
};

const PlanPerStap = ({ p, steps }) => {
  return (
    <div>
      <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 12, lineHeight: 1.5 }}>
        Elke stap heeft een eigen deadline. Zo blijft het project niet liggen tot de laatste week.
      </div>
      <div style={{ position: 'relative' }}>
        <div style={{
          position: 'absolute', left: 11, top: 8, bottom: 8,
          width: 1.5, background: 'var(--line)',
        }} />
        {steps.map((s, i) => {
          const tc = window.TEAM_COLORS[s.team];
          const isCurrent = s.id === p.huidigeBucket;
          const overdue = !s.done && window.daysUntil(s.deadline) < 0;
          const owner = s.owner ? window.medewerkerById(s.owner) : null;
          return (
            <div key={s.id} style={{ position: 'relative', paddingLeft: 34, marginBottom: 12 }}>
              <div style={{
                position: 'absolute', left: 4, top: 6,
                width: 16, height: 16, borderRadius: '50%',
                background: s.done ? 'oklch(0.58 0.12 150)' : isCurrent ? tc.dot : 'var(--paper)',
                border: s.done ? 'none' : isCurrent ? 'none' : `2px solid var(--line)`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: 'white',
                boxShadow: isCurrent ? `0 0 0 4px ${tc.bg}` : 'none',
              }}>
                {s.done && <window.Icon name="check" size={10} />}
              </div>
              <div style={{
                background: isCurrent ? tc.bg : overdue ? 'oklch(0.96 0.04 25)' : 'var(--surface-1)',
                border: overdue ? '1px solid oklch(0.80 0.12 25)' : '1px solid var(--line)',
                borderRadius: 8, padding: '9px 12px',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 2 }}>
                  <window.TeamChip team={s.team} compact />
                  <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-1)', flex: 1 }}>{s.naam}</span>
                  {!s.done && <window.DeadlineChip deadline={s.deadline} done={s.done} />}
                  {s.done && <span style={{ fontSize: 11, color: 'oklch(0.50 0.12 150)', fontWeight: 600 }}>✓ klaar</span>}
                </div>
                {owner && (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, color: 'var(--ink-2)', marginTop: 3 }}>
                    <window.Avatar m={owner} size={16} />
                    <span>{owner.naam}</span>
                    <span style={{ flex: 1 }} />
                    <span style={{ color: 'var(--ink-3)' }}>uiterlijk {window.fmtDateLong(s.deadline)}</span>
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>
      <button style={{
        display: 'flex', alignItems: 'center', gap: 6, padding: '8px 12px',
        background: 'transparent', border: '1px dashed var(--line)', borderRadius: 8,
        color: 'var(--ink-3)', fontSize: 12, cursor: 'pointer', width: '100%',
        justifyContent: 'center', marginTop: 4,
      }}>
        <window.Icon name="plus" size={12} /> Stap toevoegen of aanpassen
      </button>

      {p.notities && (
        <div style={{ marginTop: 18, padding: 14, background: 'oklch(0.97 0.02 80)', border: '1px solid oklch(0.90 0.04 80)', borderRadius: 8 }}>
          <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--ink-3)', letterSpacing: 0.4, marginBottom: 5 }}>NOTITIE</div>
          <div style={{ fontSize: 12.5, color: 'var(--ink-1)', lineHeight: 1.5 }}>{p.notities}</div>
        </div>
      )}
    </div>
  );
};

const SauzenTab = ({ p }) => {
  return (
    <div>
      <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 12 }}>
        Dit project bestaat uit {p.sauzen.length} saus{p.sauzen.length > 1 ? 'en' : ''}. Elke saus kan zelfstandig door de buckets bewegen.
      </div>
      {p.sauzen.map((s, i) => {
        const b = window.bucketById(s.bucketId);
        const prog = window.sausProgress(p, s.bucketId);
        return (
          <div key={i} style={{
            padding: 12, border: '1px solid var(--line)', borderRadius: 8,
            marginBottom: 8, background: 'var(--paper)',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
              <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-1)', flex: 1 }}>{s.naam}</span>
              <window.TeamChip team={b.team} compact />
              <span style={{ fontSize: 11, color: 'var(--ink-2)' }}>{b.naam}</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <div style={{ flex: 1, height: 4, background: 'var(--surface-2)', borderRadius: 2, overflow: 'hidden' }}>
                <div style={{ height: '100%', width: `${Math.max(prog * 100, 4)}%`, background: window.klantById(p.klant).kleur }} />
              </div>
              <span style={{ fontSize: 10.5, color: 'var(--ink-3)', fontWeight: 600, fontFamily: 'var(--mono)' }}>{Math.round(prog * 100)}%</span>
            </div>
          </div>
        );
      })}
    </div>
  );
};

const ChatTab = ({ p }) => {
  const msgs = [
    { who: 'sanne', time: 'gisteren 16:42', text: 'Monster nr 3 is vandaag verstuurd naar klant. Wacht op feedback.' },
    { who: 'marco', time: 'gisteren 17:10', text: 'Heb de receptuur iets bijgesteld — 0.4% meer zuurgraad. Nieuwe charge morgenvroeg.' },
    { who: 'wilco', time: 'vandaag 09:02', text: 'Calculatie staat klaar voor controle. Heb wel een vraag over de verpakkingskosten, zie bijlage.' },
    { who: 'patrick', time: 'vandaag 10:33', text: 'Wilco, zijn die verpakkingskosten excl. labels? Anders klopt de prijs per eenheid niet.' },
  ];
  return (
    <div>
      <div style={{ marginBottom: 14 }}>
        {msgs.map((m, i) => {
          const pers = window.medewerkerById(m.who);
          return (
            <div key={i} style={{ display: 'flex', gap: 10, marginBottom: 14 }}>
              <window.Avatar m={pers} size={28} />
              <div style={{ flex: 1 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3 }}>
                  <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink-1)' }}>{pers.naam}</span>
                  <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>{m.time}</span>
                </div>
                <div style={{ fontSize: 12.5, color: 'var(--ink-1)', lineHeight: 1.5 }}>{m.text}</div>
              </div>
            </div>
          );
        })}
      </div>
      <div style={{
        border: '1px solid var(--line)', borderRadius: 8, padding: 10,
        display: 'flex', gap: 8, alignItems: 'center',
      }}>
        <input placeholder="Opmerking toevoegen…" style={{
          flex: 1, border: 'none', outline: 'none', background: 'transparent',
          fontSize: 12.5, color: 'var(--ink-1)', fontFamily: 'inherit',
        }} />
        <button className="primary-btn" style={{
          padding: '5px 12px', background: 'var(--ink-1)', color: 'var(--paper)',
          border: 'none', borderRadius: 6, fontSize: 12, fontWeight: 600, cursor: 'pointer',
        }}>Plaats</button>
      </div>
    </div>
  );
};

const FilesTab = ({ p }) => {
  const files = [
    { naam: 'Specificatie v3.pdf', grootte: '412 kB', type: 'pdf', wie: 'linda', wanneer: 'gisteren' },
    { naam: 'Calculatie lente 2026.xlsx', grootte: '89 kB', type: 'xls', wie: 'patrick', wanneer: 'vandaag' },
    { naam: 'Klant briefing.eml', grootte: '12 kB', type: 'mail', wie: 'sanne', wanneer: '12 apr' },
    { naam: 'Monster foto.jpg', grootte: '2.1 MB', type: 'img', wie: 'marco', wanneer: '14 apr' },
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      {files.slice(0, p.bijlagen).map((f, i) => {
        const pers = window.medewerkerById(f.wie);
        return (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '9px 12px', border: '1px solid var(--line)', borderRadius: 8,
          }}>
            <div style={{
              width: 32, height: 32, borderRadius: 6, background: 'var(--surface-1)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 9, fontWeight: 700, color: 'var(--ink-2)', fontFamily: 'var(--mono)',
            }}>{f.type.toUpperCase()}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, fontWeight: 550, color: 'var(--ink-1)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{f.naam}</div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 1 }}>{f.grootte} · {pers?.naam.split(' ')[0]} · {f.wanneer}</div>
            </div>
          </div>
        );
      })}
      <button style={{
        padding: '10px 12px', background: 'transparent', border: '1px dashed var(--line)',
        borderRadius: 8, color: 'var(--ink-3)', fontSize: 12, cursor: 'pointer',
      }}>+ Bestand uploaden</button>
    </div>
  );
};

window.ProjectDetail = ProjectDetail;
