// dashboard.jsx — Admin-Dashboard für Jordan (nur DE — Admin braucht keine Übersetzung)
//
// Login als "jordan"/"alisha" → diese Komponente wird statt HomeScreen gerendert.
// Daten kommen aus Supabase via wedding_admin_list(token).

const AdminDashboard = ({ admin, onLogout }) => {
  const locale = "de-DE";

  const [guests, setGuests] = React.useState(null); // null = laden, [] = leer
  const [error,  setError]  = React.useState(null);

  const reload = React.useCallback(() => {
    setError(null);
    supaRpc("wedding_admin_list", { p_token: admin.token })
      .then(result => setGuests(Array.isArray(result) ? result : []))
      .catch(e => { console.error(e); setError(e.message || "Fehler beim Laden"); });
  }, [admin.token]);

  React.useEffect(() => { reload(); }, [reload]);

  if (error) {
    return (
      <div style={{ padding: 40, fontFamily: Fserif, color: C.ink, textAlign: "center" }}>
        <div style={{ fontSize: 22, marginBottom: 12 }}>Fehler beim Laden</div>
        <div style={{ fontFamily: Fsans, fontSize: 13, color: C.soft, marginBottom: 20 }}>{error}</div>
        <button onClick={reload} style={{ ...btn(true), padding: "12px 28px", height: "auto" }}>Erneut versuchen</button>
      </div>
    );
  }

  if (guests === null) {
    return (
      <div style={{ padding: 60, fontFamily: Fserif, fontStyle: "italic", color: C.soft, textAlign: "center" }}>
        Daten werden geladen…
      </div>
    );
  }

  const total = guests.length;
  const yes     = guests.filter(g => g.rsvp_status === "yes");
  const no      = guests.filter(g => g.rsvp_status === "no");
  const pending = guests.filter(g => !g.rsvp_status || g.rsvp_status === "pending");

  const attending  = yes.reduce((sum, g) => sum + (g.rsvp_attendees || 1), 0);
  const maxInvited = guests.reduce((sum, g) => sum + (g.max_attendees || 1), 0);

  const fmtDate = (iso) => iso ? new Date(iso).toLocaleDateString(locale, { day: "2-digit", month: "short", year: "numeric" }) : "—";
  const scopeLabel = (s) => s === "evening" ? "Nur Abend" : "Ganzer Tag";
  const dietLabel  = (d) => ({ vegetarian: "Vegetarisch", vegan: "Vegan", everything: "Isst alles" })[d] || d;

  const deadlineStr = RSVP_DEADLINE.toLocaleDateString(locale, { day: "2-digit", month: "long", year: "numeric" });

  return (
    <div className="wd-dash" style={{ background: C.bg, minHeight: "100dvh", color: C.ink }}>
      {/* Top-Bar */}
      <div className="wd-dash-topbar" style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: "20px 24px", borderBottom: `1px solid ${C.hairline}`,
        background: C.surface,
      }}>
        <div style={{ display: "flex", alignItems: "baseline", gap: 16 }}>
          <div style={{ fontFamily: Fserif, fontSize: 22 }}>J &amp; A</div>
          <div style={{ fontFamily: Fsans, fontSize: 10, letterSpacing: 2.6, color: C.soft, textTransform: "uppercase" }}>
            Dashboard · {admin.display_name}
          </div>
        </div>
        <button onClick={onLogout} style={{
          background: "transparent", border: "none", cursor: "pointer", padding: 4,
          fontFamily: Fsans, fontSize: 10, letterSpacing: 2, color: C.soft,
        }}>ABMELDEN</button>
      </div>

      {/* Hero */}
      <div className="wd-dash-hero" style={{ padding: "44px 24px 12px", textAlign: "center" }}>
        <div style={{ fontFamily: Fsans, fontSize: 10, fontWeight: 500, letterSpacing: 3.6, textTransform: "uppercase", color: C.soft, marginBottom: 12 }}>
          Übersicht der Antworten
        </div>
        <div style={{ fontFamily: Fserif, fontSize: "clamp(40px,6vw,64px)", lineHeight: 1, color: C.ink }}>
          Dashboard
        </div>
        <div style={{ fontFamily: Fserif, fontStyle: "italic", fontSize: 16, color: C.soft, marginTop: 10 }}>
          Antwortfrist: {deadlineStr}
        </div>
      </div>

      {/* Stat cards */}
      <div className="wd-dash-stats">
        <StatCard label="Gäste"     value={total}          accent="ink"/>
        <StatCard label="Zugesagt"  value={yes.length}     accent="ink"/>
        <StatCard label="Abgesagt"  value={no.length}      accent="red"/>
        <StatCard label="Ausstehend" value={pending.length} accent="soft"/>
      </div>

      {/* Charts row */}
      <div className="wd-dash-charts">
        {/* Donut */}
        <div className="wd-dash-card">
          <div className="wd-dash-card-eyebrow">Antworten</div>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "center", padding: "16px 0 8px" }}>
            <Donut yes={yes.length} no={no.length} pending={pending.length} centerText={`von ${total} geantwortet`}/>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 8 }}>
            <Legend swatch={C.ink}      label="Zugesagt"   value={yes.length}     total={total}/>
            <Legend swatch="#7A1F1F"    label="Abgesagt"   value={no.length}      total={total}/>
            <Legend swatch={C.hairline} label="Ausstehend" value={pending.length} total={total}/>
          </div>
        </div>

        {/* Attendees big number */}
        <div className="wd-dash-card">
          <div className="wd-dash-card-eyebrow">Erwartete Personen</div>
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: "24px 0 20px", flex: 1 }}>
            <div style={{ fontFamily: Fserif, fontSize: "clamp(96px,14vw,160px)", lineHeight: 0.9, color: C.ink }}>
              {attending}
            </div>
            <div style={{ fontFamily: Fsans, fontSize: 12, letterSpacing: 3, color: C.soft, marginTop: 14, textTransform: "uppercase" }}>
              von max. {maxInvited} eingeladen
            </div>
            <div style={{ width: "80%", maxWidth: 260, height: 6, background: C.hairline, marginTop: 22, position: "relative" }}>
              <div style={{ position: "absolute", inset: 0, width: `${Math.min(100, (attending/maxInvited)*100)}%`, background: C.ink }}/>
            </div>
          </div>
        </div>
      </div>

      {/* Listen */}
      <GuestList title="Zugesagt"   guests={yes}     empty="Noch keine Zusagen."   scopeLabel={scopeLabel} fmtDate={fmtDate} dietLabel={dietLabel} status="yes"/>
      <GuestList title="Abgesagt"   guests={no}      empty="Noch keine Absagen."   scopeLabel={scopeLabel} fmtDate={fmtDate} dietLabel={dietLabel} status="no"/>
      <GuestList title="Ausstehend" guests={pending} empty="Alle haben geantwortet." scopeLabel={scopeLabel} fmtDate={fmtDate} dietLabel={dietLabel} status="pending"/>

      <div style={{ padding: "60px 24px 48px", textAlign: "center" }}>
        <DecoDiv color={C.faint}/>
        <div style={{ fontFamily: Fserif, fontStyle: "italic", fontSize: 16, color: C.soft, marginTop: 18 }}>
          Mit Liebe, Jordan &amp; Alisha
        </div>
      </div>
    </div>
  );
};

// ── Bausteine ───────────────────────────────────────────────

const StatCard = ({ label, value, accent }) => {
  const accentColor = accent === "red" ? "#7A1F1F" : accent === "soft" ? C.soft : C.ink;
  return (
    <div style={{
      padding: "24px 22px",
      background: C.surface,
      border: `1px solid ${C.hairline}`,
    }}>
      <div style={{ fontFamily: Fsans, fontSize: 10, fontWeight: 500, letterSpacing: 2.6, textTransform: "uppercase", color: C.soft }}>
        {label}
      </div>
      <div style={{ fontFamily: Fserif, fontSize: "clamp(48px,7vw,72px)", lineHeight: 1, color: accentColor, marginTop: 12 }}>
        {value}
      </div>
    </div>
  );
};

const Legend = ({ swatch, label, value, total }) => {
  const pct = total ? Math.round((value / total) * 100) : 0;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10, fontFamily: Fsans, fontSize: 12 }}>
      <div style={{ width: 10, height: 10, background: swatch, flexShrink: 0 }}/>
      <div style={{ flex: 1, color: C.ink }}>{label}</div>
      <div style={{ fontVariantNumeric: "tabular-nums", color: C.ink }}>{value}</div>
      <div style={{ fontVariantNumeric: "tabular-nums", color: C.soft, width: 40, textAlign: "right" }}>{pct}%</div>
    </div>
  );
};

const Donut = ({ yes, no, pending, centerText, size = 200 }) => {
  const total = yes + no + pending || 1;
  const r = size / 2 - 18;
  const c = 2 * Math.PI * r;
  const yesLen = (yes / total) * c;
  const noLen  = (no / total) * c;
  const cx = size / 2, cy = size / 2;
  const responded = yes + no;

  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      <circle cx={cx} cy={cy} r={r} fill="none" stroke={C.hairline} strokeWidth={14}/>
      {yes > 0 && (
        <circle cx={cx} cy={cy} r={r} fill="none" stroke={C.ink} strokeWidth={14}
          strokeDasharray={`${yesLen} ${c - yesLen}`}
          transform={`rotate(-90 ${cx} ${cy})`}/>
      )}
      {no > 0 && (
        <circle cx={cx} cy={cy} r={r} fill="none" stroke="#7A1F1F" strokeWidth={14}
          strokeDasharray={`${noLen} ${c - noLen}`}
          strokeDashoffset={-yesLen}
          transform={`rotate(-90 ${cx} ${cy})`}/>
      )}

      <text x={cx} y={cy - 2} textAnchor="middle"
        style={{ fontFamily: Fserif, fontSize: 44, fill: C.ink }}>{responded}</text>
      <text x={cx} y={cy + 22} textAnchor="middle"
        style={{ fontFamily: Fsans, fontSize: 9, letterSpacing: 2, fill: C.soft }}>{centerText}</text>
    </svg>
  );
};

const GuestList = ({ title, guests, empty, scopeLabel, fmtDate, dietLabel, status }) => (
  <div className="wd-dash-list" style={{ padding: "16px 0 0" }}>
    <div style={{ padding: "0 24px", display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 14 }}>
      <div style={{ fontFamily: Fserif, fontSize: 26, color: C.ink }}>{title}</div>
      <div style={{ fontFamily: Fsans, fontSize: 11, letterSpacing: 2, color: C.soft }}>{guests.length}</div>
    </div>
    {guests.length === 0 ? (
      <div style={{ padding: "20px 24px", fontFamily: Fserif, fontStyle: "italic", fontSize: 14, color: C.soft, textAlign: "center", background: C.surface, border: `1px solid ${C.hairline}`, margin: "0 24px" }}>
        {empty}
      </div>
    ) : (
      <div className="wd-dash-table-wrap" style={{ margin: "0 0", overflowX: "auto", borderTop: `1px solid ${C.hairline}`, borderBottom: `1px solid ${C.hairline}` }}>
        <table style={{ width: "100%", borderCollapse: "collapse", fontFamily: Fsans, fontSize: 13, color: C.ink }}>
          <thead>
            <tr style={{ background: C.surface }}>
              <Th>Name</Th>
              <Th>Umfang</Th>
              {status === "yes" && <Th align="right">Pers.</Th>}
              {status !== "pending" && <Th>Geantwortet</Th>}
              {status === "yes" && <Th>Anmerkung</Th>}
            </tr>
          </thead>
          <tbody>
            {guests.map(g => (
              <tr key={g.id} style={{ borderTop: `1px solid ${C.hairline}` }}>
                <Td>
                  <div style={{ fontFamily: Fserif, fontSize: 17, color: C.ink }}>{g.display_name}</div>
                  <div style={{ fontFamily: "ui-monospace,Menlo,monospace", fontSize: 10, color: C.faint, marginTop: 2 }}>{g.username}</div>
                </Td>
                <Td><span style={{ fontSize: 11, letterSpacing: 1.2, color: C.soft, textTransform: "uppercase" }}>{scopeLabel(g.invitation_scope)}</span></Td>
                {status === "yes" && (
                  <Td align="right">
                    <span style={{ fontFamily: Fserif, fontSize: 22, color: C.ink }}>{g.rsvp_attendees}</span>
                    <span style={{ color: C.faint, fontSize: 11 }}> / {g.max_attendees}</span>
                  </Td>
                )}
                {status !== "pending" && (
                  <Td><span style={{ color: C.soft, fontSize: 12 }}>{fmtDate(g.rsvp_submitted_at)}</span></Td>
                )}
                {status === "yes" && (
                  <Td>{g.rsvp_dietary ? (
                    <span style={{ color: C.ink, fontSize: 12, fontStyle: "italic" }}>{dietLabel(g.rsvp_dietary)}</span>
                  ) : <span style={{ color: C.faint }}>—</span>}</Td>
                )}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    )}
  </div>
);

const Th = ({ children, align = "left" }) => (
  <th style={{
    textAlign: align, padding: "12px 16px",
    fontFamily: Fsans, fontSize: 9, fontWeight: 600, letterSpacing: 2.4, textTransform: "uppercase",
    color: C.soft, borderBottom: `1px solid ${C.hairline}`,
  }}>{children}</th>
);

const Td = ({ children, align = "left" }) => (
  <td style={{ textAlign: align, padding: "14px 16px", verticalAlign: "middle" }}>{children}</td>
);

Object.assign(window, { AdminDashboard });
