/* Powermieter — Admin / Hausverwaltung */
const { useState: useAS, useMemo: useAM, useEffect: useAE } = React;

const PM_STATUS = {
  none:    { label: 'Nicht eingeladen', tone: 'gray',     dot: 'var(--text-3)' },
  invited: { label: 'Eingeladen',       tone: 'gray',     dot: 'var(--text-3)' },
  interest:{ label: 'Interesse',        tone: 'accent',   dot: 'var(--accent)' },
  reg:     { label: 'Registrierung',    tone: 'accent',   dot: 'var(--accent)' },
  prep:    { label: 'Vertrag vorbereitet', tone: 'warn',  dot: 'var(--warn-500)' },
  signed:  { label: 'Abgeschlossen',    tone: 'positive', dot: 'var(--positive)' },
  active:  { label: 'Aktiviert',        tone: 'positive', dot: 'var(--positive-500)' },
};
const STATUS_ORDER = ['none', 'invited', 'interest', 'reg', 'prep', 'signed', 'active'];

const RESIDENTS = [
  { whg: 'W01', name: 'Anna Berger',      auf: 'A', etage: 'EG', status: 'active',  contact: 'a.berger@mail.de' },
  { whg: 'W02', name: 'Familie Çelik',    auf: 'A', etage: 'EG', status: 'signed',  contact: '+49 170 …' },
  { whg: 'W03', name: 'Tobias Wolf',      auf: 'A', etage: '1. OG', status: 'prep', contact: 't.wolf@mail.de' },
  { whg: 'W04', name: 'Max Mustermann',   auf: 'A', etage: '2. OG', status: 'reg',  contact: 'max@beispiel.de', flag: true },
  { whg: 'W05', name: 'Sofia Russo',      auf: 'A', etage: '2. OG', status: 'interest', contact: 's.russo@mail.de' },
  { whg: 'W06', name: 'Leon Fischer',     auf: 'A', etage: '3. OG', status: 'invited', contact: 'l.fischer@mail.de' },
  { whg: 'W07', name: 'Hr. & Fr. Yılmaz', auf: 'B', etage: 'EG', status: 'active',  contact: '+49 151 …' },
  { whg: 'W08', name: 'Clara Hoffmann',   auf: 'B', etage: 'EG', status: 'signed',  contact: 'c.hoffmann@mail.de' },
  { whg: 'W09', name: 'Jonas Krüger',     auf: 'B', etage: '1. OG', status: 'interest', contact: 'j.krueger@mail.de' },
  { whg: 'W10', name: '— leer stehend',   auf: 'B', etage: '1. OG', status: 'none', contact: '', vacant: true },
  { whg: 'W11', name: 'Mara Schulz',      auf: 'B', etage: '2. OG', status: 'invited', contact: 'm.schulz@mail.de', flag: true },
  { whg: 'W12', name: 'David Becker',     auf: 'B', etage: '3. OG', status: 'reg',  contact: 'd.becker@mail.de' },
];

function StatusBadge({ s }) {
  const st = PM_STATUS[s];
  return <span className={`pm-sbadge pm-sbadge-${st.tone}`}><span className="pm-sbadge-dot" style={{ background: st.dot }} />{st.label}</span>;
}

function AdminView({ device, tweaks = { goLiveGate: 'offen', datenfuelle: 'lueckenhaft', quote: 58 }, model = 'mieterstrom', setModel = () => {}, initialView = 'uebersicht' }) {
  const [adminView, setAdminView] = useAS(() => {
    if (initialView && initialView !== 'uebersicht') return initialView;
    try { return JSON.parse(localStorage.getItem('pm_adminview') || '"uebersicht"'); } catch { return 'uebersicht'; }
  });
  useAE(() => {
    if (new URLSearchParams(location.search).get('embed') === '1') return;
    try { localStorage.setItem('pm_adminview', JSON.stringify(adminView)); } catch {}
  }, [adminView]);
  const [wizardOpen, setWizardOpen] = useAS(false);
  const [wizardUnit, setWizardUnit] = useAS(null);
  const [drawer, setDrawer] = useAS(null);
  const openWizard = (u) => { setWizardUnit(u || null); setWizardOpen(true); };
  const [auf, setAuf] = useAS('all');
  const [etage, setEtage] = useAS('all');
  const [q, setQ] = useAS('');
  const [statusFilter, setStatusFilter] = useAS('all');
  const [noteFor, setNoteFor] = useAS(null);
  const [notes, setNotes] = useAS({ W04: 'Rückruf gewünscht — Mo nachmittags.', W11: 'Zweite Einladung am 28.05. versendet.' });
  const [showPoster, setShowPoster] = useAS(false);
  const [view, setView] = useAS('list');

  const etagen = useAM(() => [...new Set(RESIDENTS.map(r => r.etage))], []);
  const rows = useAM(() => RESIDENTS.filter(r =>
    (auf === 'all' || r.auf === auf) &&
    (etage === 'all' || r.etage === etage) &&
    (statusFilter === 'all' || r.status === statusFilter) &&
    (!q || r.name.toLowerCase().includes(q.toLowerCase()) || r.whg.toLowerCase().includes(q.toLowerCase()))
  ), [auf, etage, q, statusFilter]);

  const total = RESIDENTS.length;
  const occupied = RESIDENTS.filter(r => !r.vacant).length;
  const interested = RESIDENTS.filter(r => ['interest', 'reg', 'prep', 'signed', 'active'].includes(r.status)).length;
  const contracts = RESIDENTS.filter(r => ['signed', 'active'].includes(r.status)).length;
  const active = RESIDENTS.filter(r => r.status === 'active').length;
  const quote = Math.round(contracts / occupied * 100);
  const todo = RESIDENTS.filter(r => ['prep', 'reg'].includes(r.status) || r.flag).length;

  const breakdown = STATUS_ORDER.map(s => ({ s, n: RESIDENTS.filter(r => r.status === s).length })).filter(b => b.n > 0);

  return (
    <div className="pm-admin">
      {/* Top bar */}
      <header className="pm-admin-top">
        <div className="pm-admin-obj">
          <span className="pm-admin-obj-ic"><I.building size={22} /></span>
          <div>
            <div className="pm-admin-obj-sel">
              <h1 className="pm-admin-title">Musterstraße 12</h1>
              <I.chevDown size={18} style={{ color: 'var(--text-3)' }} />
            </div>
            <div className="pm-admin-obj-sub">10115 Berlin · 12 Wohneinheiten · 2 Aufgänge</div>
          </div>
        </div>
        <div className="pm-admin-actions">
          <Button variant="ghost" size="sm" icon={<I.qr size={17} />} onClick={() => setShowPoster(true)}>QR / Aushang</Button>
          <Button variant="ghost" size="sm" icon={<I.download size={17} />}>Export</Button>
          <Button size="sm" icon={<I.send size={16} />}>Einladungen senden</Button>
        </div>
      </header>

      <div className="pm-admin-subnav">
        {[['uebersicht', '\u00dcbersicht', I.chart], ['cockpit', 'Vertrags-Cockpit', I.signature], ['lifecycle', 'Fristen & Wechsel', I.calendar], ['weg', 'WEG-Freigabe', I.users]].map(([v, l, Ic]) => (
          <button key={v} className="pm-subtab" data-on={adminView === v ? 'true' : 'false'} onClick={() => setAdminView(v)}><Ic size={16} />{l}</button>
        ))}
      </div>

      {adminView === 'cockpit' && <div className="pm-admin-body"><ContractCockpit model={model} setModel={setModel} tweaks={tweaks} onWizard={openWizard} onUnit={setDrawer} /></div>}
      {adminView === 'lifecycle' && <div className="pm-admin-body">{window.Lifecycle ? <Lifecycle initialTab={new URLSearchParams(location.search).get('lctab') || 'fristen'} /> : null}</div>}
      {adminView === 'weg' && <div className="pm-admin-body"><WegFreigabe model={model} tweaks={tweaks} /></div>}

      {adminView === 'uebersicht' && (<div className="pm-admin-body">
        {/* KPIs */}
        <div className="pm-kpis">
          <KPI icon={<I.home />} value={total} label="Wohnungen" sub={`${occupied} bewohnt · 1 leer`} />
          <KPI icon={<I.spark />} value={interested} label="Interessenten" tone="accent" sub={`${Math.round(interested / occupied * 100)}% der Haushalte`} />
          <KPI icon={<I.signature />} value={contracts} label="Verträge" tone="positive" sub={`${active} bereits aktiv`} />
          <KPI icon={<I.chart />} value={quote + '%'} label="Teilnahmequote" tone="positive" sub="Ziel: 60%" />
          <KPI icon={<I.alert />} value={todo} label="Handlungsbedarf" tone="warn" sub="offene Vorgänge" />
        </div>

        {/* Progress + action panel */}
        <div className="pm-admin-grid">
          <div className="card card-pad">
            <div className="pm-card-head"><h3 className="pm-card-title"><I.chart size={18} /> Objekt-Fortschritt</h3><span className="chip chip-positive"><I.dot size={11} /> {quote}% abgeschlossen</span></div>
            <div className="pm-prog">
              <div className="pm-prog-bar">
                {breakdown.map(b => <span key={b.s} className={`pm-prog-seg pm-prog-${PM_STATUS[b.s].tone}`} style={{ flex: b.n, background: PM_STATUS[b.s].dot }} title={`${PM_STATUS[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: PM_STATUS[b.s].dot }} /><span>{PM_STATUS[b.s].label}</span><b className="tnum">{b.n}</b></div>
                ))}
              </div>
            </div>
          </div>

          <div className="card card-pad pm-todo-card">
            <h3 className="pm-card-title" style={{ marginBottom: 4 }}><I.alert size={18} /> Offener Handlungsbedarf</h3>
            <p className="field-hint" style={{ marginBottom: 12 }}>Vorgänge, die auf Sie warten.</p>
            <div className="pm-todo-list">
              <TodoRow icon={<I.doc />} text="3 Verträge in Vorbereitung" sub="Daten vollständig — bereit zum Versand" />
              <TodoRow icon={<I.refresh />} text="2 Einladungen ohne Reaktion" sub="seit über 7 Tagen" warn />
              <TodoRow icon={<I.user />} text="1 leer stehende Wohnung" sub="W10 · Aufgang B" />
            </div>
          </div>
        </div>

        {/* Conversion funnel */}
        <ConversionFunnel residents={RESIDENTS} />

        {/* Bewohner — Liste / Gebäude */}
        <div className="pm-admin-sectionhead">
          <h3 className="pm-card-title"><I.users size={18} /> Bewohner-Status</h3>
          <Segmented value={view} onChange={setView} options={[
            { value: 'list', label: 'Liste', icon: <I.list /> },
            { value: 'building', label: 'Gebäude', icon: <I.building /> },
          ]} />
        </div>

        {view === 'building' ? <BuildingGraphic residents={RESIDENTS} onInvite={() => {}} /> : (<>
        {/* Filters */}
        <div className="pm-filterbar">
          <div className="pm-search">
            <I.search size={17} />
            <input placeholder="Bewohner oder Wohnung suchen …" value={q} onChange={e => setQ(e.target.value)} />
          </div>
          <FilterSelect label="Aufgang" value={auf} onChange={setAuf} options={[['all', 'Alle Aufgänge'], ['A', 'Aufgang A'], ['B', 'Aufgang B']]} />
          <FilterSelect label="Etage" value={etage} onChange={setEtage} options={[['all', 'Alle Etagen'], ...etagen.map(e => [e, e])]} />
          <FilterSelect label="Status" value={statusFilter} onChange={setStatusFilter} options={[['all', 'Alle Status'], ...STATUS_ORDER.map(s => [s, PM_STATUS[s].label])]} />
          <div className="pm-filter-count">{rows.length} von {total}</div>
        </div>

        {/* Table */}
        <div className="card pm-table-card">
          <div className="pm-table">
            <div className="pm-tr pm-tr-head">
              <div className="pm-td pm-td-whg">Wohnung</div>
              <div className="pm-td pm-td-name">Bewohner</div>
              <div className="pm-td pm-td-loc">Lage</div>
              <div className="pm-td pm-td-status">Status</div>
              <div className="pm-td pm-td-act">Aktion</div>
            </div>
            {rows.map(r => (
              <React.Fragment key={r.whg}>
                <div className={'pm-tr' + (r.vacant ? ' pm-tr-vacant' : '')}>
                  <div className="pm-td pm-td-whg"><b className="mono">{r.whg}</b></div>
                  <div className="pm-td pm-td-name">
                    <span className="pm-avatar" style={{ background: r.vacant ? 'var(--surface-3)' : avatarColor(r.name) }}>{r.vacant ? '—' : initials(r.name)}</span>
                    <div style={{ minWidth: 0 }}>
                      <div className="pm-td-name-main">{r.name}{r.flag && <I.alert size={14} style={{ color: 'var(--warn-500)', marginLeft: 6, verticalAlign: '-2px' }} />}</div>
                      {r.contact && <div className="pm-td-name-sub">{r.contact}</div>}
                    </div>
                  </div>
                  <div className="pm-td pm-td-loc">Aufgang {r.auf} · {r.etage}</div>
                  <div className="pm-td pm-td-status"><StatusBadge s={r.status} /></div>
                  <div className="pm-td pm-td-act">
                    {!r.vacant && (r.status === 'invited' || r.status === 'none' || r.flag
                      ? <button className="pm-act-btn" title="Einladung erneut senden"><I.refresh size={15} /> Einladung</button>
                      : <button className="pm-act-btn pm-act-ghost" title="Details"><I.chevRight size={16} /></button>)}
                    <button className={'pm-act-icon' + (notes[r.whg] ? ' pm-act-icon-on' : '')} title="Notiz" onClick={() => setNoteFor(noteFor === r.whg ? null : r.whg)}><I.note size={16} /></button>
                  </div>
                </div>
                {noteFor === r.whg && (
                  <div className="pm-note-row">
                    <I.note size={16} style={{ color: 'var(--accent)', flex: 'none', marginTop: 8 }} />
                    <textarea className="textarea pm-note-input" placeholder="Notiz zu dieser Wohnung …" value={notes[r.whg] || ''} onChange={e => setNotes(n => ({ ...n, [r.whg]: e.target.value }))} />
                    <button className="pm-act-icon" onClick={() => setNoteFor(null)}><I.check size={16} /></button>
                  </div>
                )}
              </React.Fragment>
            ))}
            {rows.length === 0 && <div className="pm-table-empty">Keine Bewohner für diese Filter.</div>}
          </div>
        </div>
        </>)}
        <div style={{ height: 20 }} />
      </div>)}

      {wizardOpen && window.ContractWizard && <ContractWizard model={model} setModel={setModel} unit={wizardUnit} onClose={() => setWizardOpen(false)} />}
      {drawer && window.UnitDrawer && <UnitDrawer unit={drawer} model={model} tweaks={tweaks} onClose={() => setDrawer(null)} onWizard={openWizard} />}

      {showPoster && <PosterModal onClose={() => setShowPoster(false)} />}
    </div>
  );
}

function statusCat(s) {
  if (s === 'signed' || s === 'active') return 'done';
  if (s === 'interest' || s === 'reg' || s === 'prep') return 'progress';
  return 'open';
}

function ConversionFunnel({ residents }) {
  const idx = s => STATUS_ORDER.indexOf(s);
  const cnt = min => residents.filter(r => idx(r.status) >= min).length;
  const total = residents.length;
  const stages = [
    { label: 'Wohnungen gesamt',     n: total,  c: 'var(--text-3)' },
    { label: 'Eingeladen',           n: cnt(1), c: 'var(--text-2)' },
    { label: 'Interesse angemeldet', n: cnt(2), c: 'var(--accent-400)' },
    { label: 'Registriert',          n: cnt(3), c: 'var(--accent)' },
    { label: 'Vertrag abgeschlossen', n: cnt(5), c: 'var(--positive)' },
    { label: 'Aktiviert',            n: cnt(6), c: 'var(--positive-500)' },
  ];

  return (
    <div className="card card-pad">
      <div className="pm-card-head" style={{ marginBottom: 16 }}>
        <h3 className="pm-card-title"><I.filter size={17} /> Conversion-Funnel</h3>
        <span className="chip">{stages[0].n} → {stages[stages.length - 1].n} aktiviert</span>
      </div>
      <div className="pm-funnel">
        {stages.map((s, i) => {
          const pct = s.n / total * 100;
          const conv = Math.round(s.n / total * 100);
          const drop = i > 0 ? stages[i - 1].n - s.n : 0;
          return (
            <div className="pm-funnel-row" key={i}>
              <div className="pm-funnel-label">{s.label}</div>
              <div className="pm-funnel-barwrap" style={{ display: 'block', overflow: 'hidden' }}>
                <div className="pm-funnel-bar" style={{ display: 'block', width: pct + '%', background: s.c, margin: '0 auto', minWidth: 44, maxWidth: '100%', height: 34, lineHeight: '34px', textAlign: 'right', padding: '0 12px', borderRadius: 'var(--radius-sm)', boxSizing: 'border-box', whiteSpace: 'nowrap', overflow: 'hidden' }}>
                  <b className="tnum" style={{ color: '#fff', fontFamily: 'var(--font-display)', fontSize: 14, textShadow: '0 1px 2px rgba(0,0,0,.35)', verticalAlign: 'middle' }}>{s.n}</b>
                </div>
              </div>
              <div className="pm-funnel-side">
                <span className="pm-funnel-pct tnum">{conv}%</span>
                {drop > 0 && <span className="pm-funnel-drop">−{drop}</span>}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function BuildingGraphic({ residents, onInvite }) {
  const floors = ['3. OG', '2. OG', '1. OG', 'EG'];
  const aufs = ['A', 'B'];
  const [sel, setSel] = useAS(null);
  const unitsOf = (auf, fl) => residents.filter(r => r.auf === auf && r.etage === fl);

  return (
    <div className="card card-pad">
      <div className="pm-card-head" style={{ marginBottom: 16 }}>
        <h3 className="pm-card-title"><I.building size={18} /> Gebäudeansicht</h3>
        <div className="pm-bld-legend">
          <span><i style={{ background: 'var(--positive)' }} /> Abgeschlossen</span>
          <span><i style={{ background: 'var(--accent)' }} /> In Bearbeitung</span>
          <span><i style={{ background: 'var(--text-3)' }} /> Offen</span>
        </div>
      </div>

      <div className="pm-bld">
        {aufs.map(auf => (
          <div className="pm-bld-col" key={auf}>
            <div className="pm-bld-roof">
              {Array.from({ length: 7 }).map((_, i) => <span key={i} className="pm-bld-pv" />)}
              <span className="pm-bld-roof-l"><I.sun2 size={12} /> PV-Dach</span>
            </div>
            <div className="pm-bld-floors">
              {floors.map(fl => {
                const u = unitsOf(auf, fl);
                return (
                  <div className="pm-bld-floor" key={fl}>
                    <span className="pm-bld-floor-l">{fl}</span>
                    <div className="pm-bld-units">
                      {u.length ? u.map((r, k) => (
                        <button key={r.whg} className="pm-bld-unit" data-cat={statusCat(r.status)}
                          data-sel={sel && sel.whg === r.whg ? 'true' : 'false'}
                          style={{ animationDelay: (k * 0.05) + 's' }}
                          onClick={() => setSel(r)} title={`${r.whg} · ${r.name} · ${PM_STATUS[r.status].label}`}>
                          <span className="pm-bld-unit-whg mono">{r.whg}</span>
                          <span className="pm-bld-unit-dot" style={{ background: PM_STATUS[r.status].dot }} />
                        </button>
                      )) : <span className="pm-bld-unit pm-bld-unit-empty" />}
                    </div>
                  </div>
                );
              })}
            </div>
            <div className="pm-bld-base">Aufgang {auf}</div>
          </div>
        ))}
      </div>

      {sel && (
        <div className="pm-bld-detail">
          <span className="pm-avatar" style={{ background: sel.vacant ? 'var(--surface-3)' : avatarColor(sel.name) }}>{sel.vacant ? '—' : initials(sel.name)}</span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="pm-bld-detail-name">{sel.whg} · {sel.name}</div>
            <div className="pm-bld-detail-sub">Aufgang {sel.auf} · {sel.etage}{sel.contact ? ' · ' + sel.contact : ''}</div>
          </div>
          <StatusBadge s={sel.status} />
          {!sel.vacant && (statusCat(sel.status) === 'open'
            ? <Button size="sm" icon={<I.refresh size={15} />} onClick={() => onInvite && onInvite(sel)}>Einladung</Button>
            : <Button variant="ghost" size="sm" iconRight={<I.chevRight size={15} />}>Öffnen</Button>)}
          <button className="pm-iconbtn" onClick={() => setSel(null)} aria-label="Schließen"><I.x size={16} /></button>
        </div>
      )}
    </div>
  );
}

function KPI({ icon, value, label, sub, tone }) {
  return (
    <div className="pm-kpi card card-flat">
      <span className={'pm-kpi-ic' + (tone ? ' pm-kpi-ic-' + tone : '')}>{icon}</span>
      <div className="pm-kpi-value tnum" style={tone ? { color: `var(--${tone})` } : undefined}>{value}</div>
      <div className="pm-kpi-label">{label}</div>
      {sub && <div className="pm-kpi-sub">{sub}</div>}
    </div>
  );
}

function TodoRow({ icon, text, sub, warn }) {
  return (
    <div className="pm-todo-row">
      <span className={'pm-todo-ic' + (warn ? ' pm-todo-ic-warn' : '')}>{icon}</span>
      <div style={{ flex: 1, minWidth: 0 }}><div className="pm-todo-text">{text}</div><div className="pm-todo-sub">{sub}</div></div>
      <I.chevRight size={18} style={{ color: 'var(--text-3)', flex: 'none' }} />
    </div>
  );
}

function FilterSelect({ label, value, onChange, options }) {
  return (
    <div className="select-wrap pm-filter-sel">
      <select className="select" value={value} onChange={e => onChange(e.target.value)} aria-label={label}>
        {options.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
      </select>
      <I.chevDown size={16} className="select-caret" />
    </div>
  );
}

function PosterModal({ onClose }) {
  return (
    <div className="pm-modal" onClick={onClose}>
      <div className="pm-modal-inner" onClick={e => e.stopPropagation()}>
        <div className="pm-modal-bar">
          <span style={{ fontWeight: 600, color: 'var(--text)' }}>Aushang-Vorschau · DIN A4</span>
          <div style={{ display: 'flex', gap: 8 }}>
            <Button variant="ghost" size="sm" icon={<I.download size={16} />}>PDF</Button>
            <button className="pm-iconbtn" onClick={onClose}><I.x size={18} /></button>
          </div>
        </div>
        <div className="pm-poster-scroll thin-scroll">
          <div className="pm-poster">
            <div className="pm-poster-head"><Logo size={32} /><span className="chip chip-accent"><I.building size={13} /> Musterstraße 12</span></div>
            <div className="pm-poster-eyebrow">Neu für Ihr Gebäude</div>
            <h2 className="pm-poster-h1">Günstiger Solarstrom<br />direkt vom Dach.</h2>
            <p className="pm-poster-sub">Lokal erzeugt, transparent abgerechnet, in wenigen Minuten digital abgeschlossen. Die Teilnahme ist freiwillig — Ihr Strom bleibt jederzeit zuverlässig.</p>
            <div className="pm-poster-mid">
              <div className="pm-poster-qr"><QRGlyph size={150} /><span>Scannen & starten</span></div>
              <ul className="pm-poster-points">
                <li><I.wallet size={18} /> Meist günstiger als Grundversorgung</li>
                <li><I.sun2 size={18} /> Solarstrom aus Ihrem eigenen Haus</li>
                <li><I.receipt size={18} /> Monatlich & transparent</li>
                <li><I.home size={18} /> Kein Aufwand in Ihrer Wohnung</li>
              </ul>
            </div>
            <div className="pm-poster-foot">
              <span>powermieter.de/musterstrasse-12</span>
              <span>Fragen? hilfe@powermieter.de</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function initials(n) { return n.replace(/[^A-Za-zÀ-ÿ. ]/g, '').split(' ').filter(w => w && w !== '&' && !w.includes('.')).slice(0, 2).map(w => w[0]).join('').toUpperCase() || '–'; }
function avatarColor(n) { const h = [...n].reduce((a, c) => a + c.charCodeAt(0), 0) % 360; return `oklch(0.62 0.11 ${h})`; }

Object.assign(window, { AdminView });
