/* Powermieter — Vertrags-Cockpit (Hausverwaltung) */
const { useState: useCS, useMemo: useCM } = React;

function CStatusBadge({ s, size }) {
  const st = CSTATUS[s] || CSTATUS.entwurf;
  return <span className={`pm-sbadge pm-sbadge-${st.tone}${size === 'sm' ? ' pm-sbadge-sm' : ''}`}><span className="pm-sbadge-dot" style={{ background: st.dot }} />{st.label}</span>;
}

/* effective units given the "Datenfülle" tweak */
function effUnits(datenfuelle) {
  if (datenfuelle === 'vollstaendig') {
    return UNIT_CONTRACTS.map(u => u.vacant ? u : ({
      ...u, missing: [],
      status: u.status === 'daten_fehlen' ? 'bereit' : u.status,
      flag: false,
    }));
  }
  return UNIT_CONTRACTS;
}

function ModelSelector({ model, onChange }) {
  const m = VERTRAGSMODELLE[model];
  return (
    <div className="pm-modelsel">
      <div className="pm-modelsel-head">
        <span className="pm-modelsel-label">Vertragsmodell des Objekts</span>
        <span className="chip chip-accent"><I.shield size={13} /> {m.legal}</span>
      </div>
      <div className="pm-modelsel-row">
        {MODELL_ORDER.map(id => {
          const v = VERTRAGSMODELLE[id];
          return (
            <button key={id} className="pm-modelsel-opt" data-on={model === id ? 'true' : 'false'} onClick={() => onChange(id)}>
              <span className="pm-modelsel-opt-k">{v.kurz}</span>
              <span className="pm-modelsel-opt-l">{v.legal}</span>
            </button>
          );
        })}
      </div>
      <p className="pm-modelsel-desc">{m.desc}{!m.zuschlag && model !== 'pre' && <em> · Kein Mieterstromzuschlag (BNetzA).</em>}</p>
    </div>
  );
}

function ContractCockpit({ model, setModel, tweaks, onWizard, onUnit }) {
  const gate = tweaks.goLiveGate;
  const units = useCM(() => effUnits(tweaks.datenfuelle), [tweaks.datenfuelle]);
  const live = units.filter(u => !u.vacant);
  const occupied = live.length;

  const signedRanks = u => (CSTATUS_RANK[u.status] || 0) >= 4;
  const activeU = units.filter(u => u.status === 'aktiv').length;
  const signedU = units.filter(signedRanks).length;
  const missingU = units.filter(u => !u.vacant && u.missing.length).length;
  const avgReady = Math.round(live.reduce((a, u) => a + readinessPct(u, model, gate), 0) / occupied);
  const realQuote = Math.round(signedU / occupied * 100);
  const quote = tweaks.quote != null ? tweaks.quote : realQuote;

  const ready = live.filter(u => readinessPct(u, model, gate) === 100).length;
  const objReady = gate === 'erfuellt' || ready === occupied;

  const breakdown = CSTATUS_ORDER.map(s => ({ s, n: units.filter(u => u.status === s).length })).filter(b => b.n > 0);

  return (
    <div className="pm-cockpit">
      {/* Model selector */}
      <ModelSelector model={model} onChange={setModel} />

      {/* Go-Live gate banner */}
      <div className={'pm-gate' + (objReady ? ' pm-gate-ok' : '')}>
        <span className="pm-gate-ic">{objReady ? <I.shield size={22} /> : <I.lock size={22} />}</span>
        <div className="pm-gate-body">
          <div className="pm-gate-title">{objReady ? 'Objekt ist go-live-bereit' : 'Go-Live-Gate noch nicht erfüllt'}</div>
          <div className="pm-gate-sub">
            {objReady
              ? `Alle ${occupied} bewohnten Einheiten erfüllen die Vertrags- und Stammdatenlogik. Aktivierung & Abrechnung freigegeben.`
              : `${occupied - ready} von ${occupied} Einheiten erfüllen das Gate noch nicht. Powermieter rechnet erst ab, wenn Vertrag, Zustimmung und Stammdaten vollständig sind.`}
          </div>
        </div>
        <div className="pm-gate-meter">
          <div className="pm-gate-meter-v tnum">{ready}/{occupied}</div>
          <div className="pm-gate-meter-l">Einheiten bereit</div>
        </div>
      </div>

      {/* KPIs */}
      <div className="pm-kpis pm-kpis-4">
        <KPI icon={<I.home />} value={occupied} label="Aktive Einheiten" sub={`${units.length} gesamt · 1 leer`} />
        <KPI icon={<I.signature />} value={signedU} label="Verträge unterzeichnet" tone="positive" sub={`${activeU} bereits aktiv`} />
        <KPI icon={<I.alert />} value={missingU} label="Fehlende Daten" tone={missingU ? 'warn' : 'positive'} sub={missingU ? 'Einheiten unvollständig' : 'alles vollständig'} />
        <KPI icon={<I.chart />} value={avgReady + '%'} label="Ø Go-Live-Readiness" tone={avgReady === 100 ? 'positive' : 'accent'} sub={`Teilnahmequote ${quote}%`} />
      </div>

      {/* Status pipeline */}
      <div className="card card-pad">
        <div className="pm-card-head">
          <h3 className="pm-card-title"><I.filter size={17} /> Vertrags-Pipeline</h3>
          <div style={{ display: 'flex', gap: 8 }}>
            <Button variant="ghost" size="sm" icon={<I.download size={16} />}>Alle Unterlagen</Button>
            <Button size="sm" icon={<I.spark size={16} />} onClick={() => onWizard(null)}>Neuer Vertrag</Button>
          </div>
        </div>
        <div className="pm-prog">
          <div className="pm-prog-bar">
            {breakdown.map(b => <span key={b.s} className="pm-prog-seg" style={{ flex: b.n, background: CSTATUS[b.s].dot }} title={`${CSTATUS[b.s].label}: ${b.n}`} />)}
          </div>
          <div className="pm-prog-legend">
            {breakdown.map(b => (
              <div className="pm-prog-leg" key={b.s}><span className="pm-prog-leg-dot" style={{ background: CSTATUS[b.s].dot }} /><span>{CSTATUS[b.s].label}</span><b className="tnum">{b.n}</b></div>
            ))}
          </div>
        </div>
      </div>

      {/* Contract table */}
      <div className="card pm-table-card">
        <div className="pm-ctr pm-ctr-head">
          <div className="pm-ctd">Einheit</div>
          <div className="pm-ctd">Bewohner</div>
          <div className="pm-ctd">Vertragsstatus</div>
          <div className="pm-ctd">Dokumente</div>
          <div className="pm-ctd">Go-Live</div>
          <div className="pm-ctd pm-ctd-act">Aktion</div>
        </div>
        {units.map(u => {
          const pct = readinessPct(u, model, gate);
          const docs = u.vacant ? [] : unitDocs(u, model);
          const done = docs.filter(d => d.doc === 'signiert' || d.doc === 'archiviert').length;
          return (
            <div key={u.whg} className={'pm-ctr' + (u.vacant ? ' pm-tr-vacant' : '')} onClick={() => !u.vacant && onUnit(u)} style={{ cursor: u.vacant ? 'default' : 'pointer' }}>
              <div className="pm-ctd"><b className="mono">{u.whg}</b><span className="pm-ctd-loc">{u.auf} · {u.etage}</span></div>
              <div className="pm-ctd pm-ctd-name">
                <span className="pm-avatar" style={{ background: u.vacant ? 'var(--surface-3)' : avatarColor(u.name), width: 30, height: 30, fontSize: 11 }}>{u.vacant ? '—' : initials(u.name)}</span>
                <span className="pm-ctd-nm">{u.name}{u.flag && <I.alert size={13} style={{ color: 'var(--warn-500)', marginLeft: 5, verticalAlign: '-2px' }} />}</span>
              </div>
              <div className="pm-ctd"><CStatusBadge s={u.status} /></div>
              <div className="pm-ctd">
                {u.vacant ? <span className="pm-ctd-muted">—</span> : (
                  <span className="pm-docpill"><I.doc size={13} />{done}/{docs.length}<span className="pm-docpill-ver mono">{u.docVer}</span></span>
                )}
              </div>
              <div className="pm-ctd">
                {u.vacant ? <span className="pm-ctd-muted">—</span> : (
                  <span className="pm-readi">
                    <span className="pm-readi-bar"><span className="pm-readi-fill" data-full={pct === 100 ? 'true' : 'false'} style={{ width: pct + '%' }} /></span>
                    <span className="pm-readi-v tnum">{pct}%</span>
                  </span>
                )}
              </div>
              <div className="pm-ctd pm-ctd-act">
                {!u.vacant && (u.missing.length || CSTATUS_RANK[u.status] === 0
                  ? <button className="pm-act-btn" onClick={(e) => { e.stopPropagation(); onWizard(u); }}><I.signature size={14} /> Vorbereiten</button>
                  : <button className="pm-act-btn pm-act-ghost" onClick={(e) => { e.stopPropagation(); onUnit(u); }}><I.chevRight size={16} /></button>)}
              </div>
            </div>
          );
        })}
      </div>

      <p className="pm-cockpit-foot"><I.info size={14} /> IBAN, Steuernummer & Vertragspartnerdaten liegen auf <strong>Legal-Entity-Ebene</strong> ({LEGAL_ENTITY.name}), nicht je Gebäude. Jede Änderung wird revisionssicher im Audit-Log (<span className="mono">contract_events</span>) protokolliert.</p>
    </div>
  );
}

/* ---------------- Unit drawer: documents, go-live, audit ---------------- */
function UnitDrawer({ unit, model, tweaks, onClose, onWizard }) {
  const docs = unitDocs(unit, model);
  const checks = goLiveChecks(unit, model, tweaks.goLiveGate);
  const events = unitEvents(unit);
  const pct = readinessPct(unit, model, tweaks.goLiveGate);

  return (
    <div className="pm-drawer-scrim" onClick={onClose}>
      <aside className="pm-drawer thin-scroll" onClick={e => e.stopPropagation()}>
        <div className="pm-drawer-top">
          <div className="pm-drawer-id">
            <span className="pm-avatar" style={{ background: avatarColor(unit.name) }}>{initials(unit.name)}</span>
            <div>
              <div className="pm-drawer-name"><b className="mono">{unit.whg}</b> · {unit.name}</div>
              <div className="pm-drawer-sub">Aufgang {unit.auf} · {unit.etage} · {VERTRAGSMODELLE[model].kurz}</div>
            </div>
          </div>
          <button className="pm-iconbtn" onClick={onClose}><I.x size={18} /></button>
        </div>

        <div className="pm-drawer-statusbar">
          <CStatusBadge s={unit.status} />
          <span className="pm-readi" style={{ flex: 1 }}>
            <span className="pm-readi-bar"><span className="pm-readi-fill" data-full={pct === 100 ? 'true' : 'false'} style={{ width: pct + '%' }} /></span>
            <span className="pm-readi-v tnum">{pct}% bereit</span>
          </span>
        </div>

        {unit.missing.length > 0 && (
          <Alert tone="warn"><strong>Fehlende Angaben:</strong> {unit.missing.join(', ')}. Vertrag kann erst nach Vervollständigung versendet werden.</Alert>
        )}

        {/* Go-Live checklist */}
        <section className="pm-drawer-sec">
          <h4 className="pm-drawer-h"><I.checkBold size={16} /> Go-Live-Checkliste</h4>
          <div className="pm-glchecks">
            {checks.map(c => (
              <div className="pm-glcheck" data-ok={c.ok ? 'true' : 'false'} key={c.k}>
                <span className="pm-glcheck-ic">{c.ok ? <I.check size={14} /> : <I.x size={13} />}</span>
                {c.label}
              </div>
            ))}
          </div>
        </section>

        {/* Documents */}
        <section className="pm-drawer-sec">
          <h4 className="pm-drawer-h"><I.doc size={16} /> Vertragsdokumente <span className="pm-drawer-h-n">{docs.length}</span></h4>
          <div className="pm-doclist">
            {docs.map((d, i) => {
              const ds = DOC_STATUS[d.doc];
              return (
                <div className="pm-docrow" key={i}>
                  <span className="pm-docrow-ic" data-tone={ds.tone}><I.doc size={15} /></span>
                  <div className="pm-docrow-main">
                    <div className="pm-docrow-name">{d.name}{d.req && <span className="pm-docrow-req">Pflicht</span>}</div>
                    <div className="pm-docrow-meta"><span className="mono">{d.tpl}</span> · {d.ver}</div>
                  </div>
                  <span className={`pm-docstatus pm-docstatus-${ds.tone}`}>{ds.label}</span>
                </div>
              );
            })}
          </div>
        </section>

        {/* Audit log */}
        <section className="pm-drawer-sec">
          <h4 className="pm-drawer-h"><I.refresh size={16} /> Audit-Log <span className="mono pm-drawer-h-tag">contract_events</span></h4>
          <div className="pm-audit">
            {events.map((e, i) => (
              <div className="pm-audit-row" key={i}>
                <span className={'pm-audit-ic' + (e.warn ? ' pm-audit-warn' : e.good ? ' pm-audit-good' : '')}>{(I[e.icon] || I.dot)({ size: 13 })}</span>
                <div className="pm-audit-body">
                  <div className="pm-audit-t">{e.t}</div>
                  <div className="pm-audit-m">{e.who} · {e.when}</div>
                </div>
              </div>
            ))}
          </div>
        </section>

        <div className="pm-drawer-foot">
          {unit.missing.length || CSTATUS_RANK[unit.status] === 0
            ? <Button block icon={<I.signature size={16} />} onClick={() => { onClose(); onWizard(unit); }}>Vertrag im Wizard vorbereiten</Button>
            : <><Button variant="ghost" icon={<I.send size={15} />}>Erinnerung senden</Button><Button icon={<I.download size={15} />}>Unterlagen exportieren</Button></>}
        </div>
      </aside>
    </div>
  );
}

Object.assign(window, { ContractCockpit, UnitDrawer, CStatusBadge, ModelSelector, effUnits });
