/* global React, ReactDOM, MacPill */
const { useState: useMPS, useRef: useMPR, useEffect: useMPE } = React;

// ────────────────────────────────────────────────────────────
// SF Symbol-ish icons (drawn as SVG, monochromatic, white fill)
// ────────────────────────────────────────────────────────────
const Sym = ({ d, viewBox = "0 0 16 16", size = 13 }) => (
  <svg width={size} height={size} viewBox={viewBox} fill="currentColor" style={{ display: "block" }}>
    {typeof d === "string" ? <path d={d}/> : d}
  </svg>
);

const ICONS = {
  home:    <Sym d="M8 1.5L1.5 7H3v7h4v-4h2v4h4V7h1.5L8 1.5z"/>,
  mic:     <Sym d="M8 1a2.5 2.5 0 0 0-2.5 2.5v4a2.5 2.5 0 0 0 5 0v-4A2.5 2.5 0 0 0 8 1zM3.5 7.5a4.5 4.5 0 0 0 9 0h1a5.5 5.5 0 0 1-5 5.48V15h-1V12.98a5.5 5.5 0 0 1-5-5.48h1z"/>,
  bulb:    <Sym d="M8 1a5 5 0 0 0-3 9V12h6v-2a5 5 0 0 0-3-9zM6 13h4v1H6v-1zm.5 2h3v1h-3v-1z"/>,
  pin:     <Sym d="M9 1.5l-1.5 4L4 7l3 1.5V14l1 1 1-1V8.5l3-1.5-3.5-1.5L9 1.5z"/>,
  apps:    <Sym d="M2 2h5v5H2V2zm0 7h5v5H2V9zm7-7h5v5H9V2zm0 7h5v5H9V9z"/>,
  keyboard:<Sym d="M2 4h12a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1zm1 2v1h1V6H3zm2 0v1h1V6H5zm2 0v1h1V6H7zm2 0v1h1V6H9zm2 0v1h1V6h-1zm-8 2v1h1V8H3zm2 0v1h6V8H5zm7 0v1h1V8h-1zm-9 2v1h10v-1H3z"/>,
  lock:    <Sym d="M5 7V5a3 3 0 1 1 6 0v2h1a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V8a1 1 0 0 1 1-1h1zm1 0h4V5a2 2 0 1 0-4 0v2z"/>,
  info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1 1 1V13a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"/>,
  edit:    <Sym d="M11.7 2.3l2 2L5 13H3v-2l8.7-8.7zM12 4l1 1m-9 7l8.5-8.5"/>,
  trash:   <Sym d="M5 2v1H2v1h1v9a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V4h1V3h-3V2H5zm1 1h4v1H6V3zm-1 2h6v8H5V5zm1 1v6h1V6H6zm2 0v6h1V6H8zm2 0v6h1V6h-1z"/>,
  plus:    <Sym d="M7 2h2v5h5v2H9v5H7V9H2V7h5V2z"/>,
  search:  <Sym d="M7 2a5 5 0 1 0 3.1 9L13 13.9 14.4 12.5 11.5 9.6A5 5 0 0 0 7 2zm0 1.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 0 1 0-7z"/>,
  chevdown:<Sym d="M3 6l5 5 5-5H3z"/>,
  chevup:  <Sym d="M3 10l5-5 5 5H3z"/>,
  arrows:  <Sym d="M5 5l3-3 3 3H5zm0 6l3 3 3-3H5z"/>,
  gripper: <Sym d="M5 4h2v2H5V4zm4 0h2v2H9V4zM5 7h2v2H5V7zm4 0h2v2H9V7zm-4 3h2v2H5v-2zm4 0h2v2H9v-2z"/>,
  check:   <Sym d="M14 4l-7.5 8L2 7.5l1.5-1.5L6.5 9 12.5 2.5 14 4z"/>,
  speaker: <Sym d="M2 5h2.5L8 2v12L4.5 11H2V5zm9 0a4 4 0 0 1 0 6m-1.5-1.5a2 2 0 0 0 0-3"/>,
  github:  <Sym d="M8 1A7 7 0 0 0 5.8 14.6c.4 0 .5-.2.5-.4v-1.3c-2 .4-2.4-1-2.4-1-.3-.8-.7-1-.7-1-.6-.4 0-.4 0-.4.7 0 1 .7 1 .7.6 1 1.6.7 2 .6 0-.5.3-.8.5-1-1.5-.2-3.1-.8-3.1-3.4 0-.7.3-1.4.7-1.8 0-.2-.3-.9.1-2 0 0 .6-.1 2 .8a6.7 6.7 0 0 1 3.4 0c1.4-.9 2-.8 2-.8.4 1 .1 1.8.1 2 .4.4.7 1 .7 1.8 0 2.6-1.6 3.2-3 3.4.2.2.4.6.4 1.3v2c0 .2.1.4.5.4A7 7 0 0 0 8 1z"/>,
  doc:     <Sym d="M3 1h7l3 3v11H3V1zm7 0v3h3"/>,
  reorder: <Sym d="M2 4h12v1.5H2V4zm0 3.5h12V9H2V7.5zM2 11h12v1.5H2V11z"/>,
  shield:  <Sym d="M8 1l6 2v5c0 4-3 6-6 7-3-1-6-3-6-7V3l6-2z"/>,
  bell:    <Sym d="M8 1a4 4 0 0 0-4 4v3l-1 2h10l-1-2V5a4 4 0 0 0-4-4zM6 12a2 2 0 0 0 4 0H6z"/>,
};

// Category tile colors (the macOS Settings squircle look)
const NAV_COLOR = {
  home: "#5ac8fa", voice: "#ff375f", output: "#ffcc00",
  pill: "#bf5af2", rules: "#34c759", shortcut: "#0a84ff",
  privacy: "#0a84ff", about: "#8e8e93", advanced: "#ff9f0a",
};
const NAV_ICON = {
  home: "home", voice: "mic", output: "bulb", pill: "pin",
  rules: "apps", shortcut: "keyboard", privacy: "lock",
  about: "info", advanced: "wrench",
};

// ────────────────────────────────────────────────────────────
// Atoms · Switch, PopUp, Segmented, Slider, Radio, Tile, Row…
// ────────────────────────────────────────────────────────────
function Switch({ on, onChange }) {
  return <button className={`mac-switch ${on ? "on" : ""}`} onClick={() => onChange(!on)} aria-pressed={on}/>;
}

function PopUp({ value, onChange, options, width }) {
  const [open, setOpen] = useMPS(false);
  const [pos, setPos] = useMPS(null);
  const ref = useMPR(null);
  const cur = options.find(o => o.value === value) || options[0];

  const themeOf = (el) => {
    let n = el;
    while (n && n !== document.body) {
      if (n.classList && (n.classList.contains("dark") || n.classList.contains("light"))) {
        return n.classList.contains("light") ? "light" : "dark";
      }
      n = n.parentElement;
    }
    return "light";
  };

  const toggle = () => {
    if (open) { setOpen(false); return; }
    const r = ref.current.getBoundingClientRect();
    const dropH = Math.min(options.length * 26 + 8, 320);
    const below = window.innerHeight - r.bottom;
    const placeAbove = below < dropH + 12 && r.top > dropH + 12;
    setPos({
      left: r.left,
      top: placeAbove ? r.top - dropH - 4 : r.bottom + 4,
      width: Math.max(r.width, width || 0),
      theme: themeOf(ref.current),
    });
    setOpen(true);
  };

  useMPE(() => {
    if (!open) return;
    const onDoc = (e) => { if (ref.current && ref.current.contains(e.target)) return; setOpen(false); };
    const onScroll = () => setOpen(false);
    document.addEventListener("mousedown", onDoc);
    window.addEventListener("scroll", onScroll, true);
    return () => { document.removeEventListener("mousedown", onDoc); window.removeEventListener("scroll", onScroll, true); };
  }, [open]);

  return (
    <>
      <button ref={ref} className="mac-popup" style={width ? { minWidth: width } : {}} onClick={toggle}>
        <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{cur?.label}</span>
        <span className="arrows">⇅</span>
      </button>
      {open && pos && ReactDOM.createPortal(
        <div className={`macwin ${pos.theme}`} style={{ position: "fixed", left: pos.left, top: pos.top, minWidth: pos.width, width: "auto", height: "auto", borderRadius: 8, boxShadow: "none", background: "transparent" }}>
          <div className="mac-menu">
            {options.map(o => (
              <div key={o.value} className={`item ${o.value === value ? "checked" : ""}`} onClick={() => { onChange(o.value); setOpen(false); }}>
                {o.label}
              </div>
            ))}
          </div>
        </div>,
        document.body
      )}
    </>
  );
}

function Segmented({ value, onChange, options }) {
  return (
    <div className="mac-segmented">
      {options.map(o => (
        <button key={o.value} className={value === o.value ? "active" : ""} onClick={() => onChange(o.value)}>{o.label}</button>
      ))}
    </div>
  );
}

function Slider({ value, min = 0, max = 100, onChange, width = 180 }) {
  const pct = ((value - min) / (max - min)) * 100;
  return (
    <div className="mac-slider" style={{ width }} onClick={(e) => {
      const r = e.currentTarget.getBoundingClientRect();
      const x = Math.max(0, Math.min(1, (e.clientX - r.left) / r.width));
      onChange(min + x * (max - min));
    }}>
      <div className="track"/>
      <div className="fill" style={{ width: `${pct}%` }}/>
      <div className="thumb" style={{ left: `${pct}%` }}/>
    </div>
  );
}

function Radio({ checked, onChange, children }) {
  return (
    <label className={`mac-radio ${checked ? "checked" : ""}`} onClick={onChange}>
      <span className="dot"/>
      {children}
    </label>
  );
}

function Tile({ children }) { return <div className="mac-tile">{children}</div>; }
function Row({ icon, iconBg, label, desc, children }) {
  return (
    <div className="mac-row">
      {icon && (
        <span className="mac-row-icon" style={{ background: iconBg || "#8e8e93" }}>{ICONS[icon]}</span>
      )}
      <div className="meta">
        <p className="label">{label}</p>
        {desc && <p className="desc">{desc}</p>}
      </div>
      <div className="control">{children}</div>
    </div>
  );
}

function GroupLabel({ children }) { return <div className="mac-group-label">{children}</div>; }
function GroupFooter({ children }) { return <div className="mac-group-footer">{children}</div>; }

window.MacAtoms = { Switch, PopUp, Segmented, Slider, Radio, Tile, Row, GroupLabel, GroupFooter, ICONS, NAV_COLOR, NAV_ICON };
