/* admin-screens.jsx — dashboard + management screens */

/* ============ Dashboard ============ */
function AdminDashboard({ go }) {
  const a = ANALYTICS;
  const tiles = [
    { label: 'Seiten gesamt', val: '6', sub: '4 veröffentlicht', icon: 'layers' },
    { label: 'Widgets aktiv', val: '81', sub: 'über 6 Seiten', icon: 'clipboard' },
    { label: 'Page Views · 7T', val: a.kpis[0].val, sub: a.kpis[0].delta, icon: 'target', up: true },
    { label: 'Offene Prüfungen', val: '2', sub: '1 Übersetzung', icon: 'fileText' },
  ];
  return (
    <div className="ascreen">
      <AScreenHead title="Dashboard" sub="Überblick über Inhalte, Aktivität und Reichweite.">
        <button className="btn btn--ghost"><Icon name="download" size={16} /> Export</button>
        <button className="btn" onClick={() => go('builder')}><Icon name="clipboard" size={16} /> Neue Seite</button>
      </AScreenHead>

      <div className="tile-stats">
        {tiles.map((t, i) => (
          <div key={i} className="stat card">
            <div className="stat__top">
              <span className="stat__icon"><Icon name={t.icon} size={18} /></span>
              {t.up && <span className="stat__delta">{t.sub}</span>}
            </div>
            <div className="stat__val">{t.val}</div>
            <div className="stat__label">{t.label}</div>
            {!t.up && <div className="stat__sub mono">{t.sub}</div>}
          </div>
        ))}
      </div>

      <div className="dash-grid">
        <section className="card dash-panel">
          <header className="dash-panel__head">
            <h2>Zuletzt bearbeitet</h2>
            <button className="btn btn--quiet" onClick={() => go('seiten')}>Alle Seiten <Icon name="arrowRight" size={15} /></button>
          </header>
          <table className="atable">
            <thead><tr><th>Seite</th><th>Status</th><th>Sprache</th><th>Von</th><th>Wann</th></tr></thead>
            <tbody>
              {ADMIN_PAGES.slice(0, 5).map(p => (
                <tr key={p.id} onClick={() => go('builder')}>
                  <td><span className="atable__t">{p.title}</span><span className="atable__id mono">{p.id}</span></td>
                  <td><StatusPill status={p.status} /></td>
                  <td><span className="lang-tags">{p.lang.map(l => <span key={l} className="chip chip--neutral chip--mono">{l}</span>)}</span></td>
                  <td className="muted">{p.by}</td>
                  <td className="muted mono">{p.when}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </section>

        <section className="card dash-panel">
          <header className="dash-panel__head">
            <h2>Audit-Timeline</h2>
            <button className="btn btn--quiet" onClick={() => go('audit')}>Alle Logs <Icon name="arrowRight" size={15} /></button>
          </header>
          <ul className="audit-mini">
            {AUDIT_LOG.slice(0, 6).map((e, i) => (
              <li key={i}>
                <span className={`audit-dot audit-dot--${e.ev}`} />
                <span className="audit-mini__body">
                  <span className="audit-mini__ev">{AUDIT_LABEL[e.ev]}</span>
                  <span className="muted">{e.obj}</span>
                </span>
                <span className="audit-mini__meta mono">{e.user.split(' ').pop()} · {e.t}</span>
              </li>
            ))}
          </ul>
        </section>

        <section className="card dash-panel dash-panel--wide">
          <header className="dash-panel__head">
            <h2>Reichweite · letzte 7 Tage</h2>
            <button className="btn btn--quiet" onClick={() => go('analytics')}>Analytics <Icon name="arrowRight" size={15} /></button>
          </header>
          <div className="dash-chart">
            <div className="bar-chart">
              {a.views7.map((v, i) => (
                <div key={i} className="bar-chart__col">
                  <span className="bar-chart__bar" style={{ height: `${(v / Math.max(...a.views7)) * 100}%` }}>
                    <span className="bar-chart__val mono">{v}</span>
                  </span>
                  <span className="bar-chart__lbl mono">{a.days[i]}</span>
                </div>
              ))}
            </div>
            <div className="dash-chart__side">
              {a.kpis.map((k, i) => (
                <div key={i} className="kpi-mini">
                  <span className="kpi-mini__val">{k.val}</span>
                  <span className="kpi-mini__label muted">{k.label}</span>
                  <span className={`kpi-mini__delta ${k.up ? 'up' : 'down'}`}>{k.delta}</span>
                </div>
              ))}
            </div>
          </div>
        </section>
      </div>
    </div>
  );
}

/* ============ Analytics ============ */
function AdminAnalytics() {
  const a = ANALYTICS;
  return (
    <div className="ascreen">
      <AScreenHead title="Analytics" sub="Aggregierte Ereignisse pro Widget, Seite und Outbound — nach Consent.">
        <div className="seg-tabs">
          {['7 Tage', '30 Tage', 'Quartal'].map((s, i) => <button key={i} className={i === 0 ? 'is-active' : ''}>{s}</button>)}
        </div>
      </AScreenHead>

      <div className="tile-stats">
        {a.kpis.map((k, i) => (
          <div key={i} className="stat card">
            <div className="stat__val">{k.val}</div>
            <div className="stat__label">{k.label}</div>
            <div className={`stat__sub ${k.up ? 'up' : 'down'}`}>{k.delta} ggü. Vorperiode</div>
          </div>
        ))}
      </div>

      <div className="dash-grid">
        <section className="card dash-panel dash-panel--wide">
          <header className="dash-panel__head"><h2>Page Views · Verlauf</h2><span className="muted mono">events: page_view</span></header>
          <div className="bar-chart bar-chart--tall">
            {a.views7.map((v, i) => (
              <div key={i} className="bar-chart__col">
                <span className="bar-chart__bar" style={{ height: `${(v / Math.max(...a.views7)) * 100}%` }}>
                  <span className="bar-chart__val mono">{v}</span>
                </span>
                <span className="bar-chart__lbl mono">{a.days[i]}</span>
              </div>
            ))}
          </div>
        </section>

        <section className="card dash-panel">
          <header className="dash-panel__head"><h2>Top-Seiten</h2></header>
          <ul className="rank-list">
            {a.topPages.map((p, i) => (
              <li key={i}>
                <span className="rank-list__n mono">{String(i + 1).padStart(2, '0')}</span>
                <span className="rank-list__body">
                  <span className="rank-list__row"><span>{p.p}</span><span className="mono">{p.v.toLocaleString('de-DE')}</span></span>
                  <span className="rank-list__track"><span className="rank-list__fill" style={{ width: p.pct + '%' }} /></span>
                </span>
              </li>
            ))}
          </ul>
        </section>

        <section className="card dash-panel">
          <header className="dash-panel__head"><h2>Geräte</h2></header>
          <Donut data={a.device} />
        </section>

        <section className="card dash-panel">
          <header className="dash-panel__head"><h2>Sprache & Outbound</h2></header>
          <div className="split-stats">
            <div className="split-stats__col">
              <span className="split-stats__h muted">Sprache</span>
              {a.lang.map((l, i) => (
                <div key={i} className="kv-row"><span>{l.k}</span><span className="kv-track"><span className="kv-fill" style={{ width: l.v + '%' }} /></span><span className="mono">{l.v}%</span></div>
              ))}
            </div>
            <div className="split-stats__col">
              <span className="split-stats__h muted">Social-Outbound</span>
              {a.outbound.map((o, i) => (
                <div key={i} className="kv-row"><span>{o.k}</span><span className="kv-num mono">{o.v.toLocaleString('de-DE')}</span></div>
              ))}
            </div>
          </div>
          <div className="consent-strip">
            <span className="muted">Consent</span>
            <span className="consent-bar">
              <span style={{ width: a.consent.granted + '%', background: 'var(--ok)' }} title="granted" />
              <span style={{ width: a.consent.denied + '%', background: 'var(--danger)' }} title="denied" />
              <span style={{ width: a.consent.pending + '%', background: 'var(--warn)' }} title="pending" />
            </span>
            <span className="mono">{a.consent.granted}% / {a.consent.denied}% / {a.consent.pending}%</span>
          </div>
        </section>
      </div>
    </div>
  );
}

function Donut({ data }) {
  const total = data.reduce((s, d) => s + d.v, 0);
  let acc = 0;
  const colors = { oliv: '#4d5a3c', stahlblau: '#2f4f68', sandgrau: '#6a5f4c' };
  const stops = data.map(d => { const start = acc / total * 360; acc += d.v; const end = acc / total * 360; return `${colors[d.tint]} ${start}deg ${end}deg`; });
  return (
    <div className="donut-wrap">
      <div className="donut" style={{ background: `conic-gradient(${stops.join(',')})` }}><span className="donut__hole" /></div>
      <ul className="donut-legend">
        {data.map((d, i) => (
          <li key={i}><span className="donut-legend__dot" style={{ background: colors[d.tint] }} /> {d.k} <b className="mono">{d.v}%</b></li>
        ))}
      </ul>
    </div>
  );
}

/* ============ Audit ============ */
function AdminAudit() {
  return (
    <div className="ascreen">
      <AScreenHead title="Audit Logs" sub="Getrennt von Analytics gespeichert. Jede Admin-Aktion wird protokolliert.">
        <button className="btn btn--ghost"><Icon name="download" size={16} /> CSV</button>
      </AScreenHead>
      <div className="card">
        <table className="atable atable--full">
          <thead><tr><th>Ereignis</th><th>Objekt</th><th>Nutzer</th><th>Rolle</th><th>Zeit</th></tr></thead>
          <tbody>
            {AUDIT_LOG.map((e, i) => (
              <tr key={i}>
                <td><span className="audit-cell"><span className={`audit-dot audit-dot--${e.ev}`} /><span className="atable__t">{AUDIT_LABEL[e.ev]}</span><span className="atable__id mono">{e.ev}</span></span></td>
                <td className="muted">{e.obj}</td>
                <td>{e.user}</td>
                <td><span className="chip chip--neutral">{e.role}</span></td>
                <td className="muted mono">{e.t}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

Object.assign(window, { AdminDashboard, AdminAnalytics, AdminAudit, Donut });
