/* eslint-disable */
// consola.jsx — La Consola shell.
// Slide-out admin panel from the right (or sheet / floating per Tweaks).
// Manages all admin state via a reducer + exposes app/view/setViewAs
// to the view modules. Mounts to #consola-mount.

(function () {
  const { useState, useReducer, useEffect, useMemo } = React;
  const V = window.CASAM_VIEWS;

  // ─── reducer ──────────────────────────────────────────────
  function reducer(state, a) {
    switch (a.type) {
      // families
      case "family.create":
        return { ...state, families: [...state.families, a.family],
          activity: prependAct(state, { kind: "family-create", actor: "mike",
            detail: `created ${a.family.name}` }) };
      case "family.rename":
        return { ...state,
          families: state.families.map(f =>
            f.id === a.id ? { ...f, name: a.name } : f) };
      case "family.set-hoh":
        return { ...state,
          families: state.families.map(f =>
            f.id === a.id ? { ...f, headOfHousehold: a.hoh } : f) };
      case "family.dissolve": {
        const fam = state.families.find(f => f.id === a.id);
        return { ...state,
          families: state.families.filter(f => f.id !== a.id),
          users: state.users.map(u => u.familyId === a.id ? { ...u, familyId: null } : u),
          activity: prependAct(state, {
            kind: "family-dissolve", actor: "mike",
            detail: `dissolved ${fam?.name || "family"}` }) };
      }

      // users
      case "user.move-family": {
        const u = state.users.find(x => x.id === a.userId);
        const oldFam = state.families.find(f => f.id === u?.familyId);
        const newFam = state.families.find(f => f.id === a.familyId);
        return { ...state,
          users: state.users.map(x =>
            x.id === a.userId ? { ...x, familyId: a.familyId } : x),
          activity: prependAct(state, {
            kind: "family-move", actor: "mike", target: a.userId,
            detail: `${oldFam?.name || "unattached"} → ${newFam?.name || "unattached"}` }) };
      }
      case "user.set-role":
        return { ...state,
          users: state.users.map(x =>
            x.id === a.id ? { ...x, role: a.role } : x),
          activity: prependAct(state, {
            kind: "grant", actor: "mike", target: a.id,
            detail: `site role → ${a.role}` }) };
      case "user.delete":
        return { ...state,
          users: state.users.filter(x => x.id !== a.id),
          grants: state.grants.filter(g => g.userId !== a.id) };

      // grants
      case "grant.set": {
        const existing = state.grants.find(g => g.userId === a.userId && g.app === a.app);
        const grants = existing
          ? state.grants.map(g => g.userId === a.userId && g.app === a.app
              ? { ...g, role: a.role } : g)
          : [...state.grants, { userId: a.userId, app: a.app, role: a.role, grantedAt: Date.now() }];
        return { ...state, grants,
          activity: prependAct(state, {
            kind: "grant", actor: "mike", target: a.userId, app: a.app,
            detail: existing ? `${existing.role} → ${a.role}` : `granted ${a.role}` }) };
      }
      case "grant.remove":
        return { ...state,
          grants: state.grants.filter(g => !(g.userId === a.userId && g.app === a.app)),
          activity: prependAct(state, {
            kind: "revoke", actor: "mike", target: a.userId, app: a.app,
            detail: "removed grant" }) };

      // invites
      case "invite.send":
        return { ...state,
          invites: [...state.invites, a.invite],
          activity: prependAct(state, {
            kind: "invite", actor: "mike", target: a.invite.email,
            detail: `invited · ${a.invite.apps.join(" + ")}` }) };
      case "invite.cancel":
        return { ...state,
          invites: state.invites.filter(i => i.id !== a.id) };
      case "invite.resend":
        return { ...state,
          invites: state.invites.map(i =>
            i.id === a.id ? { ...i, status: "sent", sentAt: Date.now() } : i) };

      // settings
      case "settings.patch":
        return { ...state, settings: { ...state.settings, ...a.patch } };

      default: return state;
    }
  }

  function prependAct(state, partial) {
    const ev = { id: `a${Math.random().toString(36).slice(2, 7)}`, at: Date.now(), ...partial };
    return [ev, ...state.activity];
  }

  // ─── i18n (super-light) ───────────────────────────────────
  function tForTone(tone) {
    return (es, en) => tone === "english" ? en : es;
  }

  // ─── tab definitions ──────────────────────────────────────
  const TABS = [
    { id: "familias",    es: "Familias",     en: "Families",     icon: "▣" },
    { id: "personas",    es: "Personas",     en: "People",       icon: "◉" },
    { id: "permisos",    es: "Permisos",     en: "Grants",       icon: "▦" },
    { id: "invitaciones",es: "Invitaciones", en: "Invites",      icon: "✉" },
    { id: "actividad",   es: "Actividad",    en: "Activity",     icon: "◷" },
    { id: "casa",        es: "Casa",         en: "Household",    icon: "⌂" },
  ];

  // ─── La Consola root ──────────────────────────────────────
  function Consola({ open, onClose, density, tone, chrome, familiasView, permisosView,
                     viewAs, setViewAs, signedInAs }) {
    const [state, dispatch] = useReducer(reducer, window.CASAM_CONSOLA_SEED);
    const [tab, setTab] = useState("familias");
    const [detailUser, setDetailUser] = useState(null);
    const [specOpen, setSpecOpen] = useState(false);

    const t = useMemo(() => tForTone(tone), [tone]);

    // Lock body scroll when open
    useEffect(() => {
      if (!open) return;
      const prev = document.body.style.overflow;
      document.body.style.overflow = "hidden";
      return () => { document.body.style.overflow = prev; };
    }, [open]);

    // Esc closes
    useEffect(() => {
      function onKey(e) {
        if (e.key === "Escape") {
          if (specOpen) { setSpecOpen(false); return; }
          if (detailUser) { setDetailUser(null); return; }
          if (open) onClose();
        }
      }
      window.addEventListener("keydown", onKey);
      return () => window.removeEventListener("keydown", onKey);
    }, [open, detailUser, specOpen, onClose]);

    // Panel chrome geometry per Tweak
    const chromeStyles = useMemo(() => {
      if (chrome === "sheet") return {
        wrap: {
          position: "fixed", inset: 0, zIndex: 80,
          background: "rgba(10,6,3,0.55)", backdropFilter: "blur(4px)",
          display: "flex", alignItems: "flex-end",
          opacity: open ? 1 : 0,
          pointerEvents: open ? "auto" : "none",
          transition: "opacity 220ms ease",
        },
        panel: {
          width: "100%", height: "92%",
          background: "var(--bg-warm)",
          borderTop: "1px solid var(--gold-deep)",
          borderRadius: "14px 14px 0 0",
          transform: open ? "translateY(0)" : "translateY(100%)",
          transition: "transform 320ms cubic-bezier(0.2,0.7,0.3,1)",
          overflow: "hidden", position: "relative",
        },
      };
      if (chrome === "floating") return {
        wrap: {
          position: "fixed", inset: 0, zIndex: 80,
          background: "rgba(10,6,3,0.55)", backdropFilter: "blur(4px)",
          display: "flex", alignItems: "center", justifyContent: "center",
          padding: "5vh 5vw",
          opacity: open ? 1 : 0,
          pointerEvents: open ? "auto" : "none",
          transition: "opacity 220ms ease",
        },
        panel: {
          width: "100%", maxWidth: 1100, height: "90%",
          background: "var(--bg-warm)",
          border: "1px solid var(--gold-deep)",
          borderTop: "3px solid var(--gold)",
          borderRadius: 10,
          boxShadow: "0 40px 100px rgba(0,0,0,0.65)",
          transform: open ? "scale(1)" : "scale(0.96)",
          transition: "transform 240ms cubic-bezier(0.2,0.7,0.3,1)",
          overflow: "hidden", position: "relative",
        },
      };
      // default: right slide-out
      return {
        wrap: {
          position: "fixed", inset: 0, zIndex: 80,
          background: "rgba(10,6,3,0.55)", backdropFilter: "blur(4px)",
          display: "flex", justifyContent: "flex-end",
          opacity: open ? 1 : 0,
          pointerEvents: open ? "auto" : "none",
          transition: "opacity 220ms ease",
        },
        panel: {
          width: "min(780px, 96vw)", height: "100%",
          background: "var(--bg-warm)",
          borderLeft: "1px solid var(--gold-deep)",
          boxShadow: "-30px 0 80px rgba(0,0,0,0.55)",
          transform: open ? "translateX(0)" : "translateX(100%)",
          transition: "transform 320ms cubic-bezier(0.2,0.7,0.3,1)",
          overflow: "hidden", position: "relative",
        },
      };
    }, [chrome, open]);

    return (
      <div style={chromeStyles.wrap} onClick={onClose}>
        <div style={chromeStyles.panel} onClick={(e) => e.stopPropagation()}>
          {/* paper grain inside panel for warmth */}
          <div style={{
            position: "absolute", inset: 0, pointerEvents: "none",
            opacity: 0.10, zIndex: 0,
            background: "url(\"data:image/svg+xml,%3Csvg viewBox='0 0 240 240' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence baseFrequency='0.9' numOctaves='2'/%3E%3CfeColorMatrix values='0 0 0 0 0.85 0 0 0 0 0.78 0 0 0 0 0.65 0 0 0 0.5 0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E\")",
            mixBlendMode: "overlay",
          }} />

          <div style={{
            position: "relative", zIndex: 1,
            height: "100%", display: "flex", flexDirection: "column",
          }}>
            <ConsolaHeader t={t} tone={tone} onClose={onClose} signedInAs={signedInAs}
              tabs={TABS} tab={tab} setTab={setTab} state={state} />

            <div style={{
              flex: 1, overflowY: "auto",
              padding: "22px clamp(20px, 3vw, 32px) 36px",
            }}>
              {tab === "familias" && (
                <V.FamiliasView state={state} dispatch={dispatch} density={density} t={t}
                  variant={familiasView}
                  openSpec={() => setSpecOpen(true)} />
              )}
              {tab === "personas" && (
                <V.PersonasView state={state} dispatch={dispatch} density={density} t={t}
                  openDetail={setDetailUser} setViewAs={setViewAs} />
              )}
              {tab === "permisos" && (
                <V.PermisosView state={state} dispatch={dispatch} density={density} t={t}
                  variant={permisosView} />
              )}
              {tab === "invitaciones" && (
                <V.InvitacionesView state={state} dispatch={dispatch} density={density} t={t} />
              )}
              {tab === "actividad" && (
                <V.ActividadView state={state} density={density} t={t} />
              )}
              {tab === "casa" && (
                <V.CasaView state={state} dispatch={dispatch} t={t} />
              )}
            </div>

            {/* Persona detail drawer (overlays panel) */}
            {detailUser && (
              <V.PersonaDetail userId={detailUser} state={state} dispatch={dispatch}
                t={t} setViewAs={setViewAs}
                onClose={() => setDetailUser(null)} />
            )}

            {/* Migration spec overlay */}
            {specOpen && (
              <V.MigrationSpec t={t} onClose={() => setSpecOpen(false)} />
            )}
          </div>
        </div>
      </div>
    );
  }

  function ConsolaHeader({ t, tone, onClose, signedInAs, tabs, tab, setTab, state }) {
    const me = state.users.find(u => u.id === signedInAs);
    return (
      <div style={{
        padding: "20px clamp(20px, 3vw, 32px) 0",
        borderBottom: "1px solid var(--line-soft)",
        flexShrink: 0,
      }}>
        <div style={{
          display: "flex", alignItems: "flex-start", gap: 14, paddingBottom: 14,
        }}>
          <div style={{
            width: 38, height: 38, borderRadius: 4,
            background: "var(--gold)", color: "var(--bg)",
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            fontFamily: "var(--serif)", fontStyle: "italic", fontWeight: 700,
            fontSize: 22,
          }}>C</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontFamily: "var(--sans)", fontSize: 9.5, letterSpacing: 2.6,
              color: "var(--gold)", fontWeight: 700, textTransform: "uppercase",
            }}>{t("Hearth Console · admin", "Hearth Console · admin")}</div>
            <h1 style={{
              fontFamily: "var(--serif)", fontStyle: "italic", fontWeight: 500,
              fontSize: 30, color: "var(--ink)", margin: "2px 0 0",
              lineHeight: 1, letterSpacing: -0.3,
            }}>{t("La Consola", "La Consola")}</h1>
            <div style={{
              fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 13,
              color: "var(--ink-mid)", marginTop: 4,
            }}>{t(
              "lo de la casa · the household's business.",
              "the household's business · lo de la casa."
            )}</div>
          </div>
          <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 6 }}>
            <button onClick={onClose} title="Close (Esc)" style={{
              width: 36, height: 36, borderRadius: 999,
              background: "rgba(0,0,0,0.30)", color: "var(--ink-soft)",
              border: "1px solid var(--line)", cursor: "pointer",
              fontSize: 18, lineHeight: 1, fontFamily: "var(--sans)",
            }}>×</button>
            {me && (
              <div style={{
                display: "inline-flex", alignItems: "center", gap: 8,
                padding: "4px 10px 4px 4px", borderRadius: 999,
                background: "rgba(212,176,122,0.10)",
                border: "1px solid var(--gold-deep)",
              }}>
                <V.Avatar user={me} size={22} />
                <span style={{
                  fontFamily: "var(--sans)", fontSize: 9, letterSpacing: 1.6,
                  color: "var(--gold)", fontWeight: 700, textTransform: "uppercase",
                }}>admin · {me.name.split(" ")[0]}</span>
              </div>
            )}
          </div>
        </div>

        {/* tab strip */}
        <div style={{
          display: "flex", gap: 2,
          marginTop: 4, overflowX: "auto",
        }} className="consola-tabs">
          {tabs.map(T => {
            const active = tab === T.id;
            return (
              <button key={T.id} onClick={() => setTab(T.id)} style={{
                padding: "11px 16px",
                background: "transparent", border: 0, cursor: "pointer",
                color: active ? "var(--gold)" : "var(--ink-mid)",
                fontFamily: "var(--sans)", fontSize: 10.5, letterSpacing: 2,
                fontWeight: 700, textTransform: "uppercase",
                borderBottom: `2px solid ${active ? "var(--gold)" : "transparent"}`,
                whiteSpace: "nowrap",
                transition: "color 100ms ease, border-color 100ms ease",
                display: "inline-flex", alignItems: "center", gap: 8,
              }}>
                <span style={{ fontSize: 14, color: active ? "var(--gold)" : "var(--ink-faint)" }}>{T.icon}</span>
                {t(T.es, T.en)}
              </button>
            );
          })}
        </div>
      </div>
    );
  }

  Object.assign(window, { CASAM_CONSOLA: { Consola } });
})();
