// screens/menus.jsx — Dropdown-based menus (UserMenu, NotificationsDropdown, RowMenu)
// Ported from preview-d. Each one is self-contained and uses the Dropdown atom
// from lib.jsx + the dd-* CSS classes from styles.css.

// ───────────────────────── NOTIFICATIONS ─────────────────────────
function NotificationsDropdown({ ctx, triggerSize = 28 }) {
  const { data, nav } = ctx;
  const tt = ctx.tt;
  const [readIds, setReadIds] = React.useState(() => {
    try { return new Set(JSON.parse(localStorage.getItem("arco.read") || "[]")); }
    catch { return new Set(); }
  });
  React.useEffect(() => {
    localStorage.setItem("arco.read", JSON.stringify([...readIds]));
  }, [readIds]);
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef();

  React.useEffect(() => {
    if (!open) return;
    const onClick = (e) => { if (!ref.current?.contains(e.target)) setOpen(false); };
    const onKey = (e) => e.key === "Escape" && setOpen(false);
    document.addEventListener("mousedown", onClick);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onClick);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);

  const items = (data.activity || []).slice(0, 12);
  const unread = items.filter((a) => !readIds.has(a.id));
  const markAll = () => setReadIds(new Set(items.map((a) => a.id)));
  const markOne = (id) => setReadIds((s) => new Set([...s, id]));

  return (
    <div ref={ref} style={{ position: "relative", display: "inline-flex" }}>
      <button className="iconbtn sm" aria-label={tt("ui.notifications") || "Notificaciones"}
              onClick={() => setOpen((o) => !o)} style={{ position: "relative" }}>
        <Icon name="bell" size={14} />
        {unread.length > 0 && (
          <span style={{
            position: "absolute", top: 3, right: 3,
            width: 8, height: 8, borderRadius: 999,
            background: "var(--ef-accent)",
            border: "2px solid var(--ef-bg)",
          }} />
        )}
      </button>
      {open && (
        <div className="dd-menu notifications align-right" style={{ position: "absolute", top: "calc(100% + 6px)", right: 0 }}>
          <div className="dd-header">
            <b>
              {tt("notif.title") || "Notificaciones"}{" "}
              {unread.length > 0 && (
                <span className="muted" style={{ fontWeight: 400 }}>
                  · {unread.length} {tt("notif.unread") || "sin leer"}
                </span>
              )}
            </b>
            {unread.length > 0 && (
              <button className="btn ghost sm" style={{ marginLeft: "auto" }} onClick={markAll}>
                {tt("notif.markAll") || "Marcar todo"}
              </button>
            )}
          </div>
          {items.length === 0 ? (
            <div style={{ padding: 32, textAlign: "center", color: "var(--ef-muted)", fontSize: 13 }}>
              {tt("notif.allCaught") || "Todo al día."}
            </div>
          ) : items.map((a) => (
            <div key={a.id} className={`dd-row${readIds.has(a.id) ? "" : " unread"}`}
                 onClick={() => markOne(a.id)}>
              <div className={`ic ${a.tone || "default"}`}><Icon name={a.icon} size={14} /></div>
              <div className="grow" style={{ minWidth: 0 }}>
                <div dangerouslySetInnerHTML={{ __html: a.text }} style={{ lineHeight: 1.35 }} />
                {a.apt && <div style={{ fontSize: 11, color: "var(--ef-muted)", marginTop: 2 }}>{a.apt}</div>}
              </div>
              <span className="when">{relTime(a.at)}</span>
            </div>
          ))}
          <div className="dd-footer">
            <a onClick={() => { setOpen(false); nav("messages"); }}>
              {tt("notif.openAll") || "Abrir toda la actividad"} →
            </a>
          </div>
        </div>
      )}
    </div>
  );
}

// ───────────────────────── USER MENU ─────────────────────────
function UserMenu({ ctx, trigger, align = "left" }) {
  const { showToast, nav } = ctx;
  const tt = ctx.tt;
  return (
    <Dropdown align={align} trigger={trigger || (
      <button className="avatar" data-apt="ap-pez" style={{ cursor: "pointer", border: 0 }} aria-label={tt("ui.userMenu")}>SA</button>
    )}>
      <div className="profile-row">
        <div className="avatar" data-apt="ap-pez">SA</div>
        <div className="who">
          <b>Sergio del Arco</b>
          <span>sergio@delarco.es</span>
        </div>
      </div>
      <MenuItem icon="users" label={tt("user.profile") || "Perfil"} hint="⌘P"
                onClick={() => showToast && showToast("Perfil (mock)")} />
      <MenuItem icon="settings" label={tt("user.preferences") || "Preferencias"}
                onClick={() => nav("settings")} />
      <MenuItem icon="file" label={tt("user.taxExport") || "Exportar fiscal"}
                onClick={() => showToast && showToast("Exportación encolada — recibirás un email")} />
      <MenuItem icon="bell" label={tt("user.notifRules") || "Reglas de notificación"}
                onClick={() => showToast && showToast("Reglas de notificación (mock)")} />
      <MenuDivider />
      <MenuItem icon="trendUp" label={tt("user.whatsNew") || "Novedades"} hint="May ’26"
                onClick={() => showToast && showToast("Estás en la última versión.")} />
      <MenuItem icon="chat" label={tt("user.feedback") || "Enviar feedback"}
                onClick={() => showToast && showToast("Formulario de feedback (mock)")} />
      <MenuDivider />
      <MenuItem icon="x" label={tt("user.signOut") || "Cerrar sesión"} danger
                onClick={() => showToast && showToast("Sesión cerrada (mock)")} />
    </Dropdown>
  );
}

// ───────────────────────── ROW OVERFLOW ─────────────────────────
function RowMenu({ items, align = "right" }) {
  return (
    <Dropdown align={align} trigger={
      <button className="iconbtn sm" aria-label="Más opciones"
              style={{ width: 28, height: 28 }} onClick={(e) => e.stopPropagation()}>
        <Icon name="more" size={14} />
      </button>
    }>
      {items.map((it, i) => it.divider
        ? <MenuDivider key={i} />
        : <MenuItem key={i} {...it} />
      )}
    </Dropdown>
  );
}

window.NotificationsDropdown = NotificationsDropdown;
window.UserMenu = UserMenu;
window.RowMenu = RowMenu;

// ───────────────────────── RECORD MENU ─────────────────────────
// Primary CTA in /finances: dropdown that creates bills, expenses, tickets,
// tenants or bookings. Adapted from /D screens/menus.jsx with localized copy.
function RecordMenu({ ctx, label }) {
  const { openModal, tt } = ctx;
  const ttLabel = label || (tt && tt("btn.record")) || "Registrar";
  return (
    <Dropdown align="right" trigger={
      <button className="btn primary">
        <Icon name="plus" size={14} /> {ttLabel} <Icon name="chevD" size={11} />
      </button>
    }>
      <MenuHeader>{ttLabel}</MenuHeader>
      <MenuItem icon="euro"    label={(tt && tt("rec.payment")) || "Cobro recibido"}  hint="R"
                onClick={() => openModal && openModal("addBill")} />
      <MenuItem icon="receipt" label={(tt && tt("rec.expense")) || "Gasto"}           hint="E"
                onClick={() => openModal && openModal("addExpense")} />
      <MenuItem icon="file"    label={(tt && tt("rec.bill")) || "Factura"}
                onClick={() => openModal && openModal("addBill")} />
      <MenuItem icon="wrench"  label={(tt && tt("rec.ticket")) || "Incidencia de mantenimiento"} hint="T"
                onClick={() => openModal && openModal("newTicket")} />
      <MenuDivider />
      <MenuItem icon="users"   label={(tt && tt("rec.tenant")) || "Nuevo inquilino"}
                onClick={() => openModal && openModal("addTenant")} />
      <MenuItem icon="calendar" label={(tt && tt("rec.booking")) || "Nueva reserva"}
                onClick={() => openModal && openModal("newBooking")} />
    </Dropdown>
  );
}

window.RecordMenu = RecordMenu;
