// prototype-screens-4.jsx — Organisasjon (kart + ansatte) og Avtaler (oversikt + detalj)

// ═══════════════════════════════════════════════════════════════════════════
// Felles hjelpere
// ═══════════════════════════════════════════════════════════════════════════
const UNIT_TYPE_TONE = {
  styre:      { bg: '#11183d', fg: '#fff',       sub: 'Eier­representant' },
  leder:      { bg: SK.coral,  fg: '#fff',       sub: 'Daglig leder' },
  stab:       { bg: '#dee1ed', fg: SK.ink,       sub: 'Stabsfunksjon' },
  avdeling:   { bg: '#bbe8ff', fg: SK.ink,       sub: 'Avdeling' },
  entreprise: { bg: '#f2cc8f', fg: '#5b430a',    sub: 'Sosial entreprise' },
};

// ═══════════════════════════════════════════════════════════════════════════
// ORGANISASJON — kart + ansatte
// ═══════════════════════════════════════════════════════════════════════════
function OrganisationPrototype({ go }) {
  const [tab, setTab] = React.useState('kart');
  const [zoomedId, setZoomedId] = React.useState(null);

  const totalHc = ORG_UNITS.reduce((s, u) => s + (u.headcount || 0), 0) - 1; // ekskl. styret
  const stabs = ORG_UNITS.filter(u => u.type === 'stab');
  const avds  = ORG_UNITS.filter(u => u.type === 'avdeling');
  const ents  = ORG_UNITS.filter(u => u.type === 'entreprise');

  const tabs = [
    { id: 'kart', label: 'Organisasjonskart' },
    { id: 'enheter', label: `Enheter (${ORG_UNITS.length - 1})` },
    { id: 'ansatte', label: `Ansatte (${ALL_EMPLOYEES.length})` },
  ];

  const openNyEndring = (initials) => go({ screen: 'hr', tab: 'endringer', initials });

  return (
    <div className="ok-content__inner" style={{ maxWidth: 1320 }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 22 }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.08, textTransform: 'uppercase' }}>Master­data · Organisasjon</div>
          <h1 style={{ margin: '6px 0 0', fontSize: 28, fontWeight: 600, letterSpacing: -0.02 }}>Organisasjonen</h1>
          <div style={{ marginTop: 4, color: SK.soft, fontSize: 13 }}>
            {totalHc} ansatte · 4 avdelinger · 3 sosiale entrepriser · 3 stabsfunksjoner
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <Button size="sm" icon={I.download}>Eksporter</Button>
          <Button variant="primary" icon={I.plus}>Ny enhet</Button>
        </div>
      </div>

      {/* KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 14, marginBottom: 18 }}>
        <Card padded><KPI label="Ansatte totalt" value={totalHc} sub="62 fast · 70 i tiltak" /></Card>
        <Card padded><KPI label="Avdelinger" value={avds.length} sub="4 lokasjoner" /></Card>
        <Card padded><KPI label="Sosiale entrepriser" value={ents.length} sub="OK:bistro · sykkel · data" /></Card>
        <Card padded><KPI label="Stabsfunksjoner" value={stabs.length} sub="Økonomi · HR · Kvalitet" /></Card>
        <Card padded><KPI label="Sykefravær Q1" value="5,8 %" sub="mål 5,5 %" accent /></Card>
      </div>

      <Tabs tabs={tabs} value={tab} onChange={setTab} />

      {tab === 'kart' && (
        <OrgChart zoomedId={zoomedId} setZoomedId={setZoomedId} go={go} />
      )}
      {tab === 'enheter' && <UnitsList go={go} />}
      {tab === 'ansatte' && <EmployeesList onNyEndring={openNyEndring} />}
    </div>
  );
}

// ── ORGANISASJONSKART ──────────────────────────────────────────────────────
function OrgChart({ zoomedId, setZoomedId, go }) {
  const dgl = ORG_UNITS.find(u => u.id === 'dgl');
  const styret = ORG_UNITS.find(u => u.id === 'styret');
  const stabs = ORG_UNITS.filter(u => u.parent === 'dgl' && u.type === 'stab');
  const avds  = ORG_UNITS.filter(u => u.parent === 'dgl' && u.type === 'avdeling');

  return (
    <Card padded style={{ overflow: 'hidden' }}>
      <div style={{
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 24,
        padding: '30px 10px 10px', overflowX: 'auto',
      }}>
        {/* Styret */}
        <OrgNode unit={styret} onClick={() => setZoomedId('styret')} active={zoomedId === 'styret'} />
        <Connector h={20} />

        {/* Daglig leder */}
        <OrgNode unit={dgl} onClick={() => setZoomedId('dgl')} active={zoomedId === 'dgl'} highlight />
        <Connector h={20} />

        {/* Stab + Avdelinger som to-rad layout */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16, width: '100%', minWidth: 980 }}>
          {/* Stab — kompakt rad over */}
          <div>
            <div style={{ fontSize: 10.5, color: SK.soft, fontWeight: 600, letterSpacing: 0.08, textTransform: 'uppercase', textAlign: 'center', marginBottom: 8 }}>Stab</div>
            <div style={{ display: 'grid', gridTemplateColumns: `repeat(${stabs.length}, 1fr)`, gap: 14, justifyContent: 'center' }}>
              {stabs.map(u => (
                <OrgNode key={u.id} unit={u} compact onClick={() => setZoomedId(u.id)} active={zoomedId === u.id} />
              ))}
            </div>
          </div>

          {/* Linje */}
          <div style={{ height: 1, background: 'rgba(17,24,61,.1)', margin: '8px 30px 0' }} />

          {/* Avdelinger */}
          <div>
            <div style={{ fontSize: 10.5, color: SK.soft, fontWeight: 600, letterSpacing: 0.08, textTransform: 'uppercase', textAlign: 'center', marginBottom: 10 }}>Avdelinger</div>
            <div style={{ display: 'grid', gridTemplateColumns: `repeat(${avds.length}, 1fr)`, gap: 16 }}>
              {avds.map(u => {
                const children = ORG_UNITS.filter(c => c.parent === u.id);
                return (
                  <div key={u.id} style={{ display: 'flex', flexDirection: 'column', alignItems: 'stretch', gap: 10 }}>
                    <OrgNode unit={u} onClick={() => setZoomedId(u.id)} active={zoomedId === u.id} />
                    {children.length > 0 && (
                      <>
                        <Connector h={10} />
                        {children.map(c => (
                          <OrgNode key={c.id} unit={c} compact onClick={() => setZoomedId(c.id)} active={zoomedId === c.id} />
                        ))}
                      </>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>

      {zoomedId && <UnitInspector id={zoomedId} onClose={() => setZoomedId(null)} go={go} />}
    </Card>
  );
}

const Connector = ({ h = 20 }) => (
  <div style={{ width: 1.5, height: h, background: 'rgba(17,24,61,.18)' }} />
);

const OrgNode = ({ unit, compact, onClick, active, highlight }) => {
  if (!unit) return null;
  const tone = UNIT_TYPE_TONE[unit.type] || UNIT_TYPE_TONE.stab;
  const leader = unit.leader ? TEAM[unit.leader] : null;

  return (
    <div onClick={onClick} style={{
      cursor: 'pointer',
      background: SK.pureWhite,
      borderRadius: 10,
      border: `1.5px solid ${active ? SK.coral : highlight ? SK.ink : 'rgba(17,24,61,.1)'}`,
      boxShadow: active ? '0 4px 16px rgba(242,84,92,.15)' : highlight ? '0 4px 14px rgba(17,24,61,.12)' : '0 1px 2px rgba(17,24,61,.04)',
      padding: compact ? '10px 12px' : '12px 14px',
      display: 'flex', gap: 10, alignItems: 'center',
      transition: 'all .15s',
      minWidth: 0,
    }}>
      <div style={{
        width: compact ? 4 : 5, alignSelf: 'stretch', borderRadius: 99,
        background: tone.bg, flexShrink: 0,
      }} />
      {leader && (
        <EmpPhoto emp={leader} size={compact ? 28 : 34} />
      )}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: compact ? 12 : 13, fontWeight: 600, letterSpacing: -0.005, color: SK.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {unit.name}
        </div>
        <div style={{ fontSize: compact ? 10.5 : 11, color: SK.soft, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {leader ? leader.n : tone.sub}
          {unit.headcount > 1 && <span style={{ marginLeft: 6 }}>· {unit.headcount} ansatte</span>}
        </div>
      </div>
    </div>
  );
};

// ── ANSATTE-DRILLDOWN: foto + oppslag ──────────────────────────────────────
// Stabile placeholder-portretter pr. ansatt (faller tilbake til initial-avatar
// dersom bildet ikke lastes).
const EMP_FOTO_IDX = {
  KS: 5,  MR: 12, HM: 9,  ØS: 13, KK: 16, TM: 20, HE: 33, JN: 51, AN: 24, RB: 53, IH: 31,
  OB: 59, SK: 26, PL: 50, NV: 44, EH: 68, LB: 47, TÅ: 56, MS: 45, AB: 8,
};
const empFotoUrl = (i, size = 200) =>
  `https://i.pravatar.cc/${size}?img=${EMP_FOTO_IDX[i] || ((i.charCodeAt(0) % 70) + 1)}`;

// Alle enhets-id-er i treet under (og inkl.) en gitt enhet
function unitTreeIds(id) {
  const ids = [id];
  for (let n = 0; n < ids.length; n++) {
    ORG_UNITS.forEach(u => { if (u.parent === ids[n]) ids.push(u.id); });
  }
  return ids;
}
// Navngitte ansatte i enheten (inkl. underenheter), leder først
function empsInUnit(id) {
  const ids = unitTreeIds(id);
  const unit = ORG_UNITS.find(u => u.id === id);
  return ALL_EMPLOYEES
    .filter(e => ids.includes(e.enhet))
    .sort((a, b) => {
      if (unit && a.i === unit.leader) return -1;
      if (unit && b.i === unit.leader) return 1;
      return a.n.localeCompare(b.n, 'nb');
    });
}

// Foto-avatar med initial-fallback. radius='50%' → sirkel, tall → avrundet firkant
function EmpPhoto({ emp, size = 46, radius = '50%' }) {
  const [err, setErr] = React.useState(false);
  if (!emp) return null;
  if (err) {
    return <span style={{ borderRadius: radius, overflow: 'hidden', display: 'inline-flex', flexShrink: 0 }}>
      <Avatar initials={emp.i} color={emp.c} size={size} />
    </span>;
  }
  return (
    <span style={{
      width: size, height: size, borderRadius: radius, overflow: 'hidden',
      display: 'inline-block', flexShrink: 0, background: emp.c,
    }}>
      <img
        src={empFotoUrl(emp.i, size > 90 ? 240 : 96)}
        alt={emp.n}
        loading="lazy"
        onError={() => setErr(true)}
        style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
      />
    </span>
  );
}

// Klikkbart ansatt-kort i drilldown-rutenettet
function EmpCard({ emp, isLeader, onClick }) {
  const [hover, setHover] = React.useState(false);
  const kt = (typeof KONTRAKT_TYPER !== 'undefined' && KONTRAKT_TYPER[emp.kontrakt]) || null;
  return (
    <div
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        display: 'flex', gap: 11, alignItems: 'center', padding: '10px 12px',
        background: SK.pureWhite, borderRadius: 10, cursor: 'pointer',
        border: `1px solid ${hover ? SK.coral : 'rgba(17,24,61,.1)'}`,
        boxShadow: hover ? '0 4px 14px rgba(17,24,61,.10)' : '0 1px 2px rgba(17,24,61,.04)',
        transform: hover ? 'translateY(-1px)' : 'none',
        transition: 'all .15s',
      }}
    >
      <EmpPhoto emp={emp} size={46} />
      <div style={{ minWidth: 0, flex: 1 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{emp.n}</span>
          {isLeader && <span style={{ fontSize: 9, fontWeight: 700, letterSpacing: 0.04, textTransform: 'uppercase', color: SK.coral, background: SK.lightCoral, padding: '1px 6px', borderRadius: 99, flexShrink: 0 }}>Leder</span>}
        </div>
        <div style={{ fontSize: 11.5, color: SK.soft, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', marginTop: 1 }}>{emp.r}</div>
        <div style={{ display: 'flex', gap: 5, marginTop: 5, alignItems: 'center' }}>
          {kt && <span style={{ fontSize: 10, fontWeight: 600, padding: '1px 7px', borderRadius: 99, background: kt.farge + '22', color: kt.farge }}>{kt.label}</span>}
          <span style={{ fontSize: 10.5, color: SK.soft, fontVariantNumeric: 'tabular-nums' }}>{emp.stilling} %</span>
        </div>
      </div>
    </div>
  );
}

// Profilkort i overlay — stort foto + nøkkelinfo
function EmployeeProfileModal({ emp, onClose, go }) {
  React.useEffect(() => {
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [onClose]);
  if (!emp) return null;

  const kt = (typeof KONTRAKT_TYPER !== 'undefined' && KONTRAKT_TYPER[emp.kontrakt]) || null;
  const selsk = (typeof OK_SELSKAPER !== 'undefined' && OK_SELSKAPER.find(s => s.id === emp.selskap)) || null;
  const enhet = ORG_UNITS.find(u => u.id === emp.enhet);
  const leder = emp.leder ? TEAM[emp.leder] : null;
  const startetAar = emp.startet ? new Date(emp.startet).getFullYear() : null;
  const fmtNo = (iso) => {
    if (!iso) return '—';
    const d = new Date(iso);
    const mnd = ['jan','feb','mar','apr','mai','jun','jul','aug','sep','okt','nov','des'];
    return `${d.getDate()}. ${mnd[d.getMonth()]} ${d.getFullYear()}`;
  };

  const rows = [
    ['Stilling', `${emp.stilling} %`],
    ['Kontrakt', kt ? kt.label : '—'],
    ['Ansatt siden', fmtNo(emp.startet)],
    ['Arbeidsgiver', selsk ? selsk.navn : '—'],
    ['Enhet', enhet ? enhet.name : '—'],
    ['Nærmeste leder', leder ? leder.n : '—'],
  ];
  if (emp.sluttDato) rows.push(['Kontrakt utløper', fmtNo(emp.sluttDato)]);

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        background: 'rgba(17,24,61,.42)', backdropFilter: 'blur(2px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
      }}
    >
      <div
        onClick={e => e.stopPropagation()}
        style={{
          width: 'min(560px, 100%)', background: SK.pureWhite, borderRadius: 16,
          boxShadow: '0 24px 70px rgba(17,24,61,.32)', overflow: 'hidden',
        }}
      >
        {/* Header med foto */}
        <div style={{ display: 'flex', gap: 18, padding: 22, background: SK.iceBlueLight, position: 'relative' }}>
          <EmpPhoto emp={emp} size={104} radius={16} />
          <div style={{ flex: 1, minWidth: 0, paddingTop: 4 }}>
            <h2 style={{ margin: 0, fontSize: 21, fontWeight: 600, letterSpacing: -0.01 }}>{emp.n}</h2>
            <div style={{ fontSize: 13.5, color: SK.ink, marginTop: 3 }}>{emp.r}</div>
            <div style={{ display: 'flex', gap: 6, marginTop: 10, flexWrap: 'wrap' }}>
              {kt && <span style={{ fontSize: 11, fontWeight: 600, padding: '2px 9px', borderRadius: 99, background: kt.farge + '22', color: kt.farge }}>{kt.label}</span>}
              {enhet && <span style={{ fontSize: 11, fontWeight: 500, padding: '2px 9px', borderRadius: 99, background: SK.pureWhite, color: SK.soft, border: '1px solid rgba(17,24,61,.1)' }}>{enhet.name}</span>}
            </div>
          </div>
          <button onClick={onClose} style={{
            position: 'absolute', top: 14, right: 14,
            background: SK.pureWhite, border: '1px solid rgba(17,24,61,.12)', borderRadius: 99,
            width: 30, height: 30, cursor: 'pointer', color: SK.soft,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
          </button>
        </div>

        {/* Detaljer */}
        <div style={{ padding: 22 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            {rows.map(([label, value]) => (
              <div key={label} style={{ padding: '9px 11px', borderRadius: 8, background: SK.iceBlueLight }}>
                <div style={{ fontSize: 10, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase' }}>{label}</div>
                <div style={{ fontSize: 13, fontWeight: 500, marginTop: 3, color: SK.ink }}>{value}</div>
              </div>
            ))}
          </div>

          {(emp.vikarFor || emp.begrunn) && (
            <div style={{ marginTop: 12, fontSize: 12, color: SK.soft, lineHeight: 1.5, padding: '10px 12px', background: SK.lightCoral + '55', borderRadius: 8 }}>
              {emp.vikarFor ? <span>Vikar for <strong style={{ color: SK.ink }}>{emp.vikarFor}</strong></span> : emp.begrunn}
            </div>
          )}

          <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
            <Button size="sm" variant="primary" onClick={() => { onClose(); go({ screen: 'hr', tab: 'endringer', initials: emp.i }); }}>Foreslå personalendring →</Button>
            <Button size="sm" variant="ghost" onClick={onClose}>Lukk</Button>
          </div>
        </div>
      </div>
    </div>
  );
}

// Inspektor-panel under kartet
function UnitInspector({ id, onClose, go }) {
  const [selEmp, setSelEmp] = React.useState(null);
  const unit = ORG_UNITS.find(u => u.id === id);
  if (!unit) return null;
  const tone = UNIT_TYPE_TONE[unit.type];
  const leader = unit.leader ? TEAM[unit.leader] : null;
  const children = ORG_UNITS.filter(u => u.parent === id);
  const parent = unit.parent ? ORG_UNITS.find(u => u.id === unit.parent) : null;
  const agreements = AGREEMENTS.filter(a => a.enhet === id);
  const emps = empsInUnit(id);

  return (
    <div style={{ marginTop: 20, padding: 18, background: SK.iceBlueLight, borderRadius: 10, border: '1px solid rgba(17,24,61,.08)' }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 14, marginBottom: 14 }}>
        <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start', minWidth: 0 }}>
          {leader && <EmpPhoto emp={leader} size={48} radius={12} />}
          <div style={{ minWidth: 0 }}>
            <span style={{
              display: 'inline-block', padding: '2px 9px', borderRadius: 99,
              fontSize: 10.5, fontWeight: 600, letterSpacing: 0.04, textTransform: 'uppercase',
              background: tone.bg, color: tone.fg, marginBottom: 6,
            }}>{tone.sub}</span>
            <h2 style={{ margin: 0, fontSize: 20, fontWeight: 600, letterSpacing: -0.01 }}>{unit.name}</h2>
            <div style={{ fontSize: 12.5, color: SK.soft, marginTop: 4, lineHeight: 1.4 }}>{unit.desc}</div>
          </div>
        </div>
        <button onClick={onClose} style={{
          background: 'none', border: '1px solid rgba(17,24,61,.15)', borderRadius: 99,
          width: 28, height: 28, cursor: 'pointer', color: SK.soft,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
        </button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
        <Card padded>
          <div className="ok-kpi__label">Leder</div>
          {leader ? (
            <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', gap: 8 }}>
              <EmpPhoto emp={leader} size={26} />
              <div>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{leader.n}</div>
                <div style={{ fontSize: 11, color: SK.soft }}>{leader.r}</div>
              </div>
            </div>
          ) : <div style={{ fontSize: 14, marginTop: 6, color: SK.soft }}>—</div>}
        </Card>
        <Card padded>
          <div className="ok-kpi__label">Bemanning</div>
          <div className="ok-kpi__value">{unit.headcount}</div>
          <div className="ok-kpi__sub">{children.length ? `${children.length} underenheter` : 'ansatte'}</div>
        </Card>
        <Card padded>
          <div className="ok-kpi__label">Plassering</div>
          <div style={{ fontSize: 13.5, fontWeight: 500, marginTop: 6, lineHeight: 1.4 }}>{unit.location || (parent ? `Under ${parent.name}` : '—')}</div>
        </Card>
        <Card padded>
          <div className="ok-kpi__label">Avtaler knyttet til</div>
          <div className="ok-kpi__value">{agreements.length}</div>
          <div className="ok-kpi__sub">
            {agreements.length > 0 ? (
              <a onClick={() => go({ screen: 'agreements' })} style={{ color: SK.coral, cursor: 'pointer', textDecoration: 'underline' }}>se i avtale­registeret</a>
            ) : 'ingen'}
          </div>
        </Card>
      </div>

      {children.length > 0 && (
        <div style={{ marginTop: 14 }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase', marginBottom: 8 }}>Underenheter</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 10 }}>
            {children.map(c => (
              <OrgNode key={c.id} unit={c} compact />
            ))}
          </div>
        </div>
      )}

      {/* ── DRILLDOWN: ansatte i enheten ── */}
      <div style={{ marginTop: 16, borderTop: '1px solid rgba(17,24,61,.08)', paddingTop: 14 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12, marginBottom: 10, flexWrap: 'wrap' }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase' }}>
            Ansatte{children.length > 0 ? ' · inkl. underenheter' : ''}
          </div>
          <span style={{ fontSize: 11, color: SK.soft }}>
            {emps.length} navngitte{unit.headcount > emps.length ? ` · ${unit.headcount} totalt i bemanning` : ''}
          </span>
        </div>
        {emps.length === 0 ? (
          <div style={{ fontSize: 12.5, color: SK.soft, padding: '14px 0' }}>
            Ingen navngitte ansatte er registrert på denne enheten i systemet.
          </div>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(232px, 1fr))', gap: 10 }}>
            {emps.map(e => (
              <EmpCard key={e.i} emp={e} isLeader={e.i === unit.leader} onClick={() => setSelEmp(e)} />
            ))}
          </div>
        )}
      </div>

      {selEmp && <EmployeeProfileModal emp={selEmp} onClose={() => setSelEmp(null)} go={go} />}
    </div>
  );
}

// ── ENHETER-LISTE ──────────────────────────────────────────────────────────
function UnitsList({ go }) {
  return (
    <Card padded={false}>
      <table className="ok-table">
        <thead>
          <tr>
            <th style={{ paddingLeft: 18 }}>Enhet</th>
            <th>Type</th>
            <th>Leder</th>
            <th>Bemanning</th>
            <th>Plassering</th>
            <th>Tilhører</th>
          </tr>
        </thead>
        <tbody>
          {ORG_UNITS.filter(u => u.id !== 'styret').map(u => {
            const tone = UNIT_TYPE_TONE[u.type];
            const leader = u.leader ? TEAM[u.leader] : null;
            const parent = u.parent ? ORG_UNITS.find(x => x.id === u.parent) : null;
            return (
              <tr key={u.id}>
                <td style={{ paddingLeft: 18 }}>
                  <div style={{ fontWeight: 600 }}>{u.name}</div>
                  <div style={{ fontSize: 11.5, color: SK.soft, marginTop: 2 }}>{u.desc}</div>
                </td>
                <td>
                  <span style={{ display: 'inline-block', padding: '2px 9px', borderRadius: 99, fontSize: 10.5, fontWeight: 600, background: tone.bg, color: tone.fg }}>
                    {tone.sub}
                  </span>
                </td>
                <td>
                  {leader ? (
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                      <Avatar initials={leader.i} color={leader.c} size={20} />
                      <span style={{ fontSize: 12 }}>{leader.n}</span>
                    </div>
                  ) : <span style={{ color: SK.soft }}>—</span>}
                </td>
                <td style={{ fontSize: 12.5, fontWeight: 600 }}>{u.headcount}</td>
                <td style={{ fontSize: 12, color: SK.soft }}>{u.location || '—'}</td>
                <td style={{ fontSize: 12 }}>{parent?.name || 'Topp'}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </Card>
  );
}

// Ansatte-listen er nå definert i personal-screens.jsx (m/kontrakt-info,
// filter og foreslå-endring-knapp pr. linje).

// ═══════════════════════════════════════════════════════════════════════════
// AVTALER — oversikt med filter + detalj-drawer
// ═══════════════════════════════════════════════════════════════════════════
const AGRTYPE_LABEL = {
  rammeavtale:   'Rammeavtale',
  tilskudd:      'Tilskudd',
  samarbeid:     'Samarbeid',
  leie:          'Leieavtale',
  leverandør:    'Leverandør',
  kunde:         'Kundeavtale',
  sertifisering: 'Sertifisering',
};

const STATUS_TONE = {
  aktiv:          { bg: '#dbeed8', fg: '#1b6a2e' },
  utløper:        { bg: '#fdeac8', fg: '#8e5a05' },
  reforhandles:   { bg: '#fdeac8', fg: '#8e5a05' },
  resertifiseres: { bg: '#fdeac8', fg: '#8e5a05' },
  utløpt:         { bg: '#f8d3d5', fg: '#8a1620' },
};

function AgreementsMock({ go }) {
  const [search, setSearch] = React.useState('');
  const [typeFilter, setTypeFilter] = React.useState('all');
  const [statusFilter, setStatusFilter] = React.useState('all');
  const [selected, setSelected] = React.useState(null);
  const [sortBy, setSortBy] = React.useState('slutt');
  const [sortDir, setSortDir] = React.useState('asc');

  const sortedAgr = React.useMemo(() => {
    let a = AGREEMENTS.slice();
    if (search) a = a.filter(x =>
      x.name.toLowerCase().includes(search.toLowerCase()) ||
      x.motpart.toLowerCase().includes(search.toLowerCase()) ||
      x.lokasjon.toLowerCase().includes(search.toLowerCase())
    );
    if (typeFilter !== 'all') a = a.filter(x => x.type === typeFilter);
    if (statusFilter !== 'all') a = a.filter(x => x.status === statusFilter);
    a.sort((x, y) => {
      let vx = x[sortBy], vy = y[sortBy];
      if (sortBy === 'arsverdi' || sortBy === 'totalverdi') { vx = +vx; vy = +vy; }
      if (vx < vy) return sortDir === 'asc' ? -1 : 1;
      if (vx > vy) return sortDir === 'asc' ? 1 : -1;
      return 0;
    });
    return a;
  }, [search, typeFilter, statusFilter, sortBy, sortDir]);

  const totalAars = sortedAgr.reduce((s, a) => s + a.arsverdi, 0);
  const totalSum  = sortedAgr.reduce((s, a) => s + a.totalverdi, 0);
  const utloperSnart = AGREEMENTS.filter(a => daysUntil(a.slutt) < 180 && daysUntil(a.slutt) >= 0).length;
  const kritisk = AGREEMENTS.filter(a => daysUntil(a.slutt) < 30 && daysUntil(a.slutt) >= 0).length;

  const toggleSort = (k) => {
    if (sortBy === k) setSortDir(d => d === 'asc' ? 'desc' : 'asc');
    else { setSortBy(k); setSortDir('asc'); }
  };
  const SortHead = ({ k, children, style }) => (
    <th onClick={() => toggleSort(k)} className={sortBy === k ? 'sorted' : ''} style={style}>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
        {children}
        {sortBy === k ? (sortDir === 'asc' ? I.arrowUp : I.arrowDown) : null}
      </span>
    </th>
  );

  return (
    <div className="ok-content__inner" style={{ maxWidth: 1320 }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 22 }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.08, textTransform: 'uppercase' }}>Master­data · Avtaleregister</div>
          <h1 style={{ margin: '6px 0 0', fontSize: 28, fontWeight: 600, letterSpacing: -0.02 }}>Avtaler</h1>
          <div style={{ marginTop: 4, color: SK.soft, fontSize: 13 }}>
            {AGREEMENTS.length} avtaler · {kritisk > 0 && <span style={{ color: SK.coral, fontWeight: 600 }}>{kritisk} kritisk frist innen 30 dgr · </span>}{utloperSnart} utløper innen 6 mnd
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <Button size="sm" icon={I.download}>Eksporter</Button>
          <Button variant="primary" icon={I.plus}>Registrer avtale</Button>
        </div>
      </div>

      {/* KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 14, marginBottom: 18 }}>
        <Card padded><KPI label="Aktive avtaler" value={AGREEMENTS.filter(a => a.status === 'aktiv').length} sub={`av ${AGREEMENTS.length} totalt`} /></Card>
        <Card padded><KPI label="Årsverdi" value={`${(totalAars / 1_000_000).toFixed(1)} mill`} sub="kr per år" /></Card>
        <Card padded><KPI label="Total verdi" value={`${(totalSum / 1_000_000).toFixed(0)} mill`} sub="over avtaleperiode" /></Card>
        <Card padded><KPI label="Utløper < 6 mnd" value={utloperSnart} sub="krever oppfølging" accent={utloperSnart > 0} /></Card>
        <Card padded><KPI label="Kritisk (< 30 dgr)" value={kritisk} sub={kritisk ? 'reforhandling pågår' : 'ingen'} accent={kritisk > 0} /></Card>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: selected ? '1fr 380px' : '1fr', gap: 14, alignItems: 'flex-start' }}>
        <Card padded={false}>
          {/* Filter-rad */}
          <div style={{ padding: '12px 16px', display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap', borderBottom: '1px solid rgba(17,24,61,.08)' }}>
            <input className="ok-input ok-input--search" placeholder="Søk avtale, motpart, sted…" value={search} onChange={e => setSearch(e.target.value)} style={{ maxWidth: 280 }} />
            <select value={typeFilter} onChange={e => setTypeFilter(e.target.value)} className="ok-input" style={{ maxWidth: 180, padding: '6px 10px' }}>
              <option value="all">Alle typer</option>
              {Object.entries(AGRTYPE_LABEL).map(([k, l]) => <option key={k} value={k}>{l}</option>)}
            </select>
            <div style={{ display: 'flex', gap: 4 }}>
              {[['all', 'Alle'], ['aktiv', 'Aktive'], ['utløper', 'Utløper'], ['reforhandles', 'Reforhandles']].map(([k, l]) => (
                <button key={k} onClick={() => setStatusFilter(k)} className="ok-btn ok-btn--sm" style={{
                  background: statusFilter === k ? SK.ink : 'transparent',
                  color: statusFilter === k ? '#fff' : SK.ink,
                  borderColor: statusFilter === k ? SK.ink : 'rgba(17,24,61,.15)',
                }}>{l}</button>
              ))}
            </div>
            <span style={{ marginLeft: 'auto', fontSize: 11.5, color: SK.soft }}>
              {sortedAgr.length} av {AGREEMENTS.length}
            </span>
          </div>

          <div style={{ overflow: 'auto' }}>
            <table className="ok-table">
              <thead>
                <tr>
                  <SortHead k="name" style={{ paddingLeft: 18 }}>Avtale</SortHead>
                  <SortHead k="type">Type</SortHead>
                  <SortHead k="lokasjon">Lokasjon</SortHead>
                  <SortHead k="slutt">Avtaletid</SortHead>
                  <SortHead k="arsverdi">Årsverdi</SortHead>
                  <th>Eier</th>
                  <SortHead k="status">Status</SortHead>
                </tr>
              </thead>
              <tbody>
                {sortedAgr.map(a => {
                  const eier = TEAM[a.eier];
                  const days = daysUntil(a.slutt);
                  const tone = STATUS_TONE[a.status] || STATUS_TONE.aktiv;
                  const isSelected = selected?.id === a.id;
                  return (
                    <tr key={a.id}
                      onClick={() => setSelected(a)}
                      style={{
                        background: isSelected ? SK.iceBlueLight : 'transparent',
                        borderLeft: isSelected ? `3px solid ${SK.coral}` : '3px solid transparent',
                      }}
                    >
                      <td style={{ paddingLeft: 18 }}>
                        <div style={{ fontWeight: 600, fontSize: 12.5 }}>{a.name}</div>
                        <div style={{ fontSize: 11, color: SK.soft, marginTop: 2 }}>{a.motpart}</div>
                      </td>
                      <td style={{ fontSize: 12 }}>{AGRTYPE_LABEL[a.type]}</td>
                      <td style={{ fontSize: 12 }}>{a.lokasjon}</td>
                      <td>
                        <div style={{ fontSize: 12, fontWeight: 500 }}>
                          {fmtDate(a.start)} – {fmtDate(a.slutt)}
                        </div>
                        <div style={{ fontSize: 11, color: days < 30 ? SK.coral : days < 180 ? SK.warn : SK.soft, marginTop: 2, fontWeight: days < 180 ? 600 : 400 }}>
                          {days < 0 ? `${Math.abs(days)} dgr utløpt` :
                            days === 0 ? 'utløper i dag' :
                            `${days} dgr igjen`}
                        </div>
                      </td>
                      <td style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: 'nowrap' }}>
                        {fmtKr(a.arsverdi)}
                        <div style={{ fontSize: 10.5, color: SK.soft, fontWeight: 400, marginTop: 1 }}>kr/år</div>
                      </td>
                      <td>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                          <Avatar initials={eier?.i} color={eier?.c} size={20} />
                          <span style={{ fontSize: 12 }}>{eier?.n.split(' ')[0]}</span>
                        </div>
                      </td>
                      <td>
                        <span style={{
                          display: 'inline-flex', alignItems: 'center', gap: 5,
                          padding: '3px 9px', borderRadius: 99, fontSize: 10.5, fontWeight: 600,
                          background: tone.bg, color: tone.fg, letterSpacing: 0.01,
                        }}>
                          <span style={{ width: 6, height: 6, borderRadius: '50%', background: tone.fg }} />
                          {a.status[0].toUpperCase() + a.status.slice(1)}
                        </span>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </Card>

        {selected && <AgreementDetail agreement={selected} onClose={() => setSelected(null)} go={go} />}
      </div>
    </div>
  );
}

function AgreementDetail({ agreement: a, onClose, go }) {
  const eier = TEAM[a.eier];
  const enhet = ORG_UNITS.find(u => u.id === a.enhet);
  const days = daysUntil(a.slutt);
  const totalDays = (new Date(a.slutt) - new Date(a.start)) / 86400000;
  const passedDays = (new Date('2026-05-21') - new Date(a.start)) / 86400000;
  const pct = Math.max(0, Math.min(100, Math.round(passedDays / totalDays * 100)));
  const tone = STATUS_TONE[a.status] || STATUS_TONE.aktiv;

  return (
    <Card padded style={{ position: 'sticky', top: 0 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 12, gap: 8 }}>
        <div>
          <div style={{ fontSize: 10.5, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase' }}>
            {AGRTYPE_LABEL[a.type]} · {a.docId}
          </div>
          <h2 style={{ margin: '4px 0 0', fontSize: 17, fontWeight: 600, letterSpacing: -0.01, lineHeight: 1.3 }}>{a.name}</h2>
        </div>
        <button onClick={onClose} style={{
          background: 'none', border: '1px solid rgba(17,24,61,.15)', borderRadius: 99,
          width: 26, height: 26, cursor: 'pointer', color: SK.soft,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
        </button>
      </div>

      <div style={{ fontSize: 12, color: SK.soft, lineHeight: 1.5, marginBottom: 14 }}>{a.desc}</div>

      {/* Status banner */}
      <div style={{ padding: '10px 12px', borderRadius: 8, background: tone.bg + '50', marginBottom: 14, display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{ width: 8, height: 8, borderRadius: '50%', background: tone.fg, flexShrink: 0 }} />
        <div style={{ fontSize: 12, color: tone.fg, fontWeight: 600 }}>
          {a.status[0].toUpperCase() + a.status.slice(1)}{a.varsel ? ` · ${a.varsel}` : ''}
        </div>
      </div>

      {/* Avtaletid progress */}
      <div style={{ marginBottom: 14 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
          <span style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase' }}>Avtaletid</span>
          <span style={{ fontSize: 11, color: SK.soft }}>{pct}% gått</span>
        </div>
        <Progress value={pct} status={days < 30 ? 'delay' : days < 180 ? 'risk' : 'track'} />
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: 11.5 }}>
          <span style={{ fontWeight: 600 }}>{fmtDate(a.start)}</span>
          <span style={{ fontWeight: 600, color: days < 180 ? SK.coral : SK.ink }}>{fmtDate(a.slutt)}</span>
        </div>
      </div>

      {/* Detalj-grid */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 14 }}>
        <DetailCell label="Årsverdi" value={`kr ${fmtKr(a.arsverdi)}`} />
        <DetailCell label="Total" value={`kr ${fmtKr(a.totalverdi)}`} />
        <DetailCell label="Avtaleeier" value={
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <Avatar initials={eier?.i} color={eier?.c} size={18} />
            {eier?.n.split(' ')[0]}
          </span>
        } />
        <DetailCell label="Enhet" value={
          enhet ? <a onClick={() => go({ screen: 'org' })} style={{ color: SK.coral, cursor: 'pointer' }}>{enhet.name}</a> : a.avdeling
        } />
        <DetailCell label="Lokasjon" value={a.lokasjon} />
        <DetailCell label="Motpart" value={`${a.motpart}${a.motpartType === 'offentlig' ? ' · off.' : ''}`} />
        <DetailCell label="Fornyelse" value={a.fornyelse} />
        <DetailCell label="Risiko" value={
          <span style={{
            padding: '1px 8px', borderRadius: 4, fontSize: 10.5, fontWeight: 600,
            background: a.risiko === 'høy' ? SK.lightCoral : a.risiko === 'middels' ? '#fdeac8' : '#dbeed8',
            color: a.risiko === 'høy' ? '#8a1620' : a.risiko === 'middels' ? '#8e5a05' : '#1b6a2e',
          }}>{a.risiko}</span>
        } />
        {a.arealM2 && <DetailCell label="Areal" value={`${a.arealM2} m²`} />}
      </div>

      {/* Aksjoner */}
      <div style={{ display: 'flex', gap: 6, marginBottom: 14, flexWrap: 'wrap' }}>
        <Button size="sm" variant="primary" icon={I.doc}>Åpne dokument</Button>
        <Button size="sm">Reforhandle</Button>
        <Button size="sm" variant="ghost">Logg</Button>
      </div>

      {/* Tidslinje */}
      <div style={{ borderTop: '1px solid rgba(17,24,61,.08)', paddingTop: 12 }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase', marginBottom: 8 }}>Tidslinje</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, fontSize: 12 }}>
          {[
            { d: fmtDate(a.start), t: 'Avtale signert', icon: '✓' },
            { d: '21. mai', t: 'I dag (' + pct + '% av avtaletid)', icon: '◆', active: true },
            ...(a.varsel ? [{ d: '—', t: a.varsel, icon: '!', alert: true }] : []),
            { d: fmtDate(a.slutt), t: 'Utløp', icon: '×' },
          ].map((x, i) => (
            <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
              <span style={{
                minWidth: 20, height: 20, borderRadius: '50%',
                background: x.alert ? SK.coral : x.active ? SK.ink : SK.iceBlue,
                color: x.alert || x.active ? '#fff' : SK.soft,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 11, fontWeight: 700, flexShrink: 0,
              }}>{x.icon}</span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 11.5, fontWeight: x.active || x.alert ? 600 : 500, color: x.alert ? SK.coral : SK.ink }}>{x.t}</div>
                <div style={{ fontSize: 10.5, color: SK.soft, marginTop: 1 }}>{x.d}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </Card>
  );
}

const DetailCell = ({ label, value }) => (
  <div style={{ padding: '8px 10px', borderRadius: 6, background: SK.iceBlueLight }}>
    <div style={{ fontSize: 10, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase' }}>{label}</div>
    <div style={{ fontSize: 12.5, fontWeight: 500, marginTop: 3, color: SK.ink }}>{value}</div>
  </div>
);

// Agreements håndteres av avtaler.jsx — eksporteres som AgreementsMock som fallback
// Organisation håndteres av organisasjon.jsx — eksporteres som OrganisationMock som fallback
const OrganisationMock = OrganisationPrototype;
Object.assign(window, { AgreementsMock, OrganisationMock });
