/* global React, Avatar,
   IconCheck, IconChevron, IconBell, IconSettings, IconLogout,
   IconStar, IconReceipt, IconUsers, IconShield, IconClock, IconChart,
   IconFile, IconBuilding, IconUpload, IconCheckCirc, IconX, IconExt
*/
const { useState: useStateM, useEffect: useEffectM, useRef: useRefM } = React;

/* ============================================================
   Popover — anchored floating panel with click-outside
   ============================================================ */
function Popover({ open, anchor, onClose, align = "right", offsetY = 8, width = 320, children }) {
  const ref = useRefM(null);

  useEffectM(() => {
    if (!open) return;
    const onDoc = (e) => {
      if (ref.current && !ref.current.contains(e.target) && anchor && !anchor.contains(e.target)) {
        onClose();
      }
    };
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("mousedown", onDoc);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDoc);
      document.removeEventListener("keydown", onKey);
    };
  }, [open, anchor, onClose]);

  if (!open || !anchor) return null;
  const rect = anchor.getBoundingClientRect();
  const right  = align === "right"  ? (window.innerWidth - rect.right) : undefined;
  const left   = align === "left"   ? rect.left : undefined;
  const bottom = align === "bottom-left" ? (window.innerHeight - rect.top + offsetY) : undefined;
  const top    = (align === "right" || align === "left") ? (rect.bottom + offsetY) : undefined;

  return (
    <div
      ref={ref}
      style={{
        position: "fixed",
        top, right, left, bottom,
        width,
        background: "var(--bg-secondary)",
        border: "1px solid var(--border-default)",
        borderRadius: "var(--radius-lg)",
        boxShadow: "var(--elevation-3)",
        zIndex: 1000,
        overflow: "hidden",
        animation: "popover-in 160ms var(--easing-emphasized)",
      }}>
      <style>{`
        @keyframes popover-in {
          from { opacity: 0; transform: translateY(-4px) scale(0.98); }
          to   { opacity: 1; transform: translateY(0)    scale(1); }
        }
      `}</style>
      {children}
    </div>
  );
}

/* ============================================================
   Notifications menu
   ============================================================ */
const NOTIFS = [
  { group: "TODAY", items: [
    { id: 1, kind: "review",  unread: true,  who: "Tinker Post Bangkok", action: "submitted a new invoice", what: "INV-2026-0518 · ฿178,880", when: "5 min ago" },
    { id: 2, kind: "approve", unread: true,  who: "Ananda V.",           action: "approved your invoice",   what: "INV-2026-0418 · ready for payment Jun 02", when: "1h ago" },
    { id: 3, kind: "vendor",  unread: true,  who: "Tee S.",              action: "submitted a new vendor",  what: "Citylight Banners Ltd. — needs your review", when: "2h ago" },
  ]},
  { group: "YESTERDAY", items: [
    { id: 4, kind: "quality", unread: false, who: "Drayage Express",     action: "flagged for quality review", what: "Score dropped to 2.4 · 3 weekend dispatches late", when: "Yesterday · 16:24" },
    { id: 5, kind: "pay",     unread: false, who: "MotionReach Finance", action: "released payment",          what: "฿128,500 → Echo Audio Post", when: "Yesterday · 11:18" },
  ]},
  { group: "EARLIER THIS WEEK", items: [
    { id: 6, kind: "expire",  unread: false, who: "Compliance",          action: "document expiring soon",    what: "Bright Lens — VAT cert expires May 30", when: "May 14" },
    { id: 7, kind: "vendor",  unread: false, who: "Aim K.",              action: "approved a vendor",         what: "Reverb Sound Stage is now active", when: "May 14" },
  ]},
];

const NOTIF_META = {
  review:  { color: "var(--info)",    icon: <IconReceipt size={13}/> },
  approve: { color: "var(--success)", icon: <IconCheck size={13}/> },
  vendor:  { color: "var(--accent)",  icon: <IconUsers size={13}/> },
  quality: { color: "var(--warning)", icon: <IconStar size={13}/> },
  pay:     { color: "var(--success)", icon: <IconReceipt size={13}/> },
  expire:  { color: "var(--warning)", icon: <IconClock size={13}/> },
};

function NotificationsMenu({ onClose }) {
  const [tab, setTab] = useStateM("all");
  const unread = NOTIFS.flatMap(g => g.items).filter(n => n.unread).length;

  return (
    <div>
      <div style={{
        padding: "12px 16px",
        borderBottom: "1px solid var(--border-subtle)",
        display: "flex", alignItems: "center", justifyContent: "space-between",
      }}>
        <div>
          <div style={{fontSize: 14, fontWeight: 500}}>Notifications</div>
          <div className="muted" style={{fontSize: 11, marginTop: 2}}>{unread} unread · synced just now</div>
        </div>
        <button className="btn btn-ghost btn-sm" style={{height: 26, padding: "0 8px", fontSize: 11}}>Mark all read</button>
      </div>

      <div style={{display: "flex", gap: 4, padding: "8px 12px", borderBottom: "1px solid var(--border-subtle)"}}>
        {[["all","All"],["unread","Unread"],["mentions","@Mentions"]].map(([id, lbl]) => (
          <button key={id}
            className={"chip " + (tab === id ? "active" : "")}
            onClick={() => setTab(id)}
            style={{height: 24, fontSize: 11}}>
            {lbl}
            {id === "unread" && <span style={{marginLeft: 4, color: tab === "unread" ? "var(--text-primary)" : "var(--text-tertiary)"}}>{unread}</span>}
          </button>
        ))}
      </div>

      <div style={{maxHeight: 440, overflowY: "auto"}}>
        {NOTIFS.map(group => {
          const items = tab === "unread" ? group.items.filter(n => n.unread) : group.items;
          if (items.length === 0) return null;
          return (
            <div key={group.group}>
              <div style={{
                padding: "10px 16px 6px",
                fontSize: 10, textTransform: "uppercase", letterSpacing: "0.08em",
                color: "var(--text-tertiary)",
                fontFamily: "var(--font-mono)",
              }}>{group.group}</div>
              {items.map(n => {
                const m = NOTIF_META[n.kind];
                return (
                  <div key={n.id} style={{
                    display: "grid",
                    gridTemplateColumns: "28px 1fr 8px",
                    gap: 10,
                    padding: "10px 16px",
                    cursor: "pointer",
                    background: n.unread ? "color-mix(in oklab, var(--accent) 5%, transparent)" : "transparent",
                    transition: "background 0.15s",
                    alignItems: "flex-start",
                  }}
                  onMouseEnter={e => e.currentTarget.style.background = "var(--interactive-secondary)"}
                  onMouseLeave={e => e.currentTarget.style.background = n.unread ? "color-mix(in oklab, var(--accent) 5%, transparent)" : "transparent"}>
                    <span style={{
                      width: 28, height: 28, borderRadius: "50%",
                      background: `color-mix(in oklab, ${m.color} 18%, transparent)`,
                      color: m.color,
                      display: "inline-flex", alignItems: "center", justifyContent: "center",
                      flexShrink: 0, marginTop: 1,
                    }}>{m.icon}</span>
                    <div style={{minWidth: 0}}>
                      <div style={{fontSize: 12.5, lineHeight: 1.45, color: "var(--text-primary)"}}>
                        <span style={{fontWeight: 400}}>{n.who}</span>
                        <span className="muted"> {n.action}</span>
                      </div>
                      <div className="muted" style={{fontSize: 11, marginTop: 3, lineHeight: 1.4}}>
                        {n.what}
                      </div>
                      <div className="muted" style={{fontSize: 10, marginTop: 4, fontFamily: "var(--font-mono)"}}>{n.when}</div>
                    </div>
                    {n.unread && (
                      <span style={{
                        width: 6, height: 6, borderRadius: "50%",
                        background: "var(--accent)",
                        marginTop: 6,
                      }}></span>
                    )}
                  </div>
                );
              })}
            </div>
          );
        })}
      </div>

      <div style={{
        padding: "10px 16px",
        borderTop: "1px solid var(--border-subtle)",
        display: "flex", justifyContent: "space-between", alignItems: "center",
        background: "var(--bg-primary)",
      }}>
        <button className="btn btn-ghost btn-sm" style={{height: 28, padding: "0 8px", fontSize: 12}}>Settings</button>
        <button className="btn btn-ghost btn-sm" style={{height: 28, padding: "0 8px", fontSize: 12}}>View all <IconChevron size={11}/></button>
      </div>
    </div>
  );
}

/* ============================================================
   Settings menu (top-right gear & sidebar bottom)
   ============================================================ */
function SettingsMenu({ theme, density, accent, onTheme, onDensity, onAccent, isPortal, onClose }) {
  const ThemeBtn = ({ value, label, icon }) => (
    <button onClick={() => onTheme(value)}
      style={{
        flex: 1,
        display: "flex", alignItems: "center", justifyContent: "center", gap: 6,
        padding: "8px 10px",
        background: theme === value ? "var(--bg-primary)" : "transparent",
        border: "1px solid " + (theme === value ? "var(--border-default)" : "transparent"),
        boxShadow: theme === value ? "var(--elevation-1)" : "none",
        borderRadius: 6,
        color: theme === value ? "var(--text-primary)" : "var(--text-secondary)",
        fontFamily: "var(--font-en)", fontSize: 12, fontWeight: 400,
        cursor: "pointer",
      }}>
      {icon} {label}
    </button>
  );

  const SunIcon = (p) => (
    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="4"/>
      <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/>
    </svg>
  );
  const MoonIcon = (p) => (
    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 12.8A9 9 0 1111.2 3a7 7 0 009.8 9.8z"/>
    </svg>
  );

  return (
    <div>
      <div style={{
        padding: "14px 16px",
        borderBottom: "1px solid var(--border-subtle)",
        display: "flex", gap: 12, alignItems: "center",
      }}>
        <Avatar name={isPortal ? "Tinker Post Bangkok" : "Ploy Veerasakul"} size="lg"/>
        <div style={{flex: 1, minWidth: 0}}>
          <div style={{fontSize: 13, fontWeight: 400}}>
            {isPortal ? "Praew Wattana" : "Ploy Veerasakul"}
          </div>
          <div className="muted" style={{fontSize: 11, marginTop: 2}}>
            {isPortal ? "Tinker Post Bangkok · Owner" : "Project Manager · MotionReach"}
          </div>
          <div className="muted" style={{fontSize: 10, marginTop: 2, fontFamily: "var(--font-mono)"}}>
            {isPortal ? "praew@tinkerpost.co.th" : "ploy@motionreach.co"}
          </div>
        </div>
      </div>

      <div style={{padding: "12px 16px", borderBottom: "1px solid var(--border-subtle)"}}>
        <div style={{
          fontSize: 10, textTransform: "uppercase", letterSpacing: "0.08em",
          color: "var(--text-tertiary)", marginBottom: 8, fontWeight: 500,
        }}>Appearance</div>

        <div style={{
          display: "flex", gap: 4,
          background: "var(--interactive-secondary)",
          padding: 3, borderRadius: 8,
          marginBottom: 12,
        }}>
          <ThemeBtn value="light" label="Light" icon={<SunIcon/>}/>
          <ThemeBtn value="dark"  label="Dark"  icon={<MoonIcon/>}/>
        </div>

        <div style={{display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8}}>
          <span style={{fontSize: 12, color: "var(--text-secondary)"}}>Density</span>
          <div style={{display: "flex", gap: 4}}>
            {[["compact","Compact"],["comfortable","Comfy"]].map(([id, lbl]) => (
              <button key={id} onClick={() => onDensity(id)}
                style={{
                  padding: "4px 10px",
                  fontSize: 11,
                  background: density === id ? "var(--bg-primary)" : "transparent",
                  border: "1px solid " + (density === id ? "var(--border-default)" : "var(--border-subtle)"),
                  borderRadius: 6,
                  color: density === id ? "var(--text-primary)" : "var(--text-secondary)",
                  cursor: "pointer",
                  fontFamily: "var(--font-en)",
                }}>{lbl}</button>
            ))}
          </div>
        </div>

        <div style={{display: "flex", justifyContent: "space-between", alignItems: "center"}}>
          <span style={{fontSize: 12, color: "var(--text-secondary)"}}>Accent</span>
          <div style={{display: "flex", gap: 6}}>
            {[
              ["#9437FF","Purple"],
              ["#73FDFF","Cyan"],
              ["#22D389","Emerald"],
              ["#FFB547","Amber"],
            ].map(([hex, lbl]) => (
              <button key={hex} title={lbl} onClick={() => onAccent(hex)}
                style={{
                  width: 18, height: 18, borderRadius: "50%",
                  background: hex,
                  border: accent === hex ? "2px solid var(--text-primary)" : "2px solid transparent",
                  outline: "1px solid var(--border-default)",
                  cursor: "pointer", padding: 0,
                }}/>
            ))}
          </div>
        </div>
      </div>

      <div style={{padding: 6}}>
        {[
          [<IconUsers size={14}/>,    "Account & profile"],
          [<IconBell size={14}/>,     "Notification preferences"],
          [<IconShield size={14}/>,   "Security & sign-in"],
          [<IconFile size={14}/>,     "Keyboard shortcuts"],
          [<IconExt size={14}/>,      "Help & support"],
        ].map(([icon, label], i) => (
          <button key={i}
            style={{
              width: "100%",
              display: "flex", alignItems: "center", gap: 10,
              padding: "8px 10px",
              background: "transparent",
              border: "none",
              color: "var(--text-secondary)",
              fontSize: 13,
              fontFamily: "var(--font-en)", fontWeight: 300,
              borderRadius: 6,
              cursor: "pointer",
              textAlign: "left",
            }}
            onMouseEnter={e => { e.currentTarget.style.background = "var(--interactive-secondary)"; e.currentTarget.style.color = "var(--text-primary)"; }}
            onMouseLeave={e => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--text-secondary)"; }}>
            <span style={{width: 16, display: "inline-flex", justifyContent: "center", color: "var(--text-tertiary)"}}>{icon}</span>
            {label}
          </button>
        ))}
      </div>

      <div style={{borderTop: "1px solid var(--border-subtle)", padding: 6}}>
        <button
          style={{
            width: "100%",
            display: "flex", alignItems: "center", gap: 10,
            padding: "8px 10px",
            background: "transparent",
            border: "none",
            color: "var(--danger)",
            fontSize: 13,
            fontFamily: "var(--font-en)", fontWeight: 300,
            borderRadius: 6,
            cursor: "pointer",
            textAlign: "left",
          }}
          onMouseEnter={e => e.currentTarget.style.background = "color-mix(in oklab, var(--danger) 10%, transparent)"}
          onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
          <span style={{width: 16, display: "inline-flex", justifyContent: "center"}}><IconLogout size={14}/></span>
          Sign out
        </button>
      </div>

      <div style={{
        padding: "10px 16px",
        background: "var(--bg-primary)",
        borderTop: "1px solid var(--border-subtle)",
        display: "flex", justifyContent: "space-between", alignItems: "center",
        fontSize: 10, color: "var(--text-tertiary)", fontFamily: "var(--font-mono)",
      }}>
        <span>Vendor OS · v0.4.2</span>
        <span>{isPortal ? "Portal" : "Workspace"}</span>
      </div>
    </div>
  );
}

Object.assign(window, { Popover, NotificationsMenu, SettingsMenu });
