/* Banyan Pharmacy — UI primitives (Terrace Stone & Ink) */
const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;
const D = window.DATA;

function cx(...a) { return a.filter(Boolean).join(" "); }

/* ---------- Inline icons (Lucide-style, 1.5px, never filled) ------------- */
const Icon = ({ size = 16, stroke = 1.5, children, style }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
    strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, ...style }}>
    {children}
  </svg>
);
const Icons = {
  chevDown: (p) => <Icon {...p}><path d="m6 9 6 6 6-6" /></Icon>,
  chevRight: (p) => <Icon {...p}><path d="m9 6 6 6-6 6" /></Icon>,
  chevLeft: (p) => <Icon {...p}><path d="m15 6-6 6 6 6" /></Icon>,
  close: (p) => <Icon {...p}><path d="M18 6 6 18M6 6l12 12" /></Icon>,
  check: (p) => <Icon {...p}><path d="M20 6 9 17l-5-5" /></Icon>,
  arrowLeft: (p) => <Icon {...p}><path d="M19 12H5M12 19l-7-7 7-7" /></Icon>,
  plus: (p) => <Icon {...p}><path d="M5 12h14M12 5v14" /></Icon>,
  mapPin: (p) => <Icon {...p}><path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z" /><circle cx="12" cy="10" r="3" /></Icon>,
  cross: (p) => <Icon {...p}><path d="M9 3h6v6h6v6h-6v6H9v-6H3V9h6z" /></Icon>,
  store: (p) => <Icon {...p}><path d="M3 9 4.5 4h15L21 9M4 9v10a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1V9M4 9h16" /></Icon>,
  truck: (p) => <Icon {...p}><path d="M10 17h4V5H2v12h2M14 8h4l3 4v5h-3M9 17a2 2 0 1 1-4 0 2 2 0 0 1 4 0Zm12 0a2 2 0 1 1-4 0 2 2 0 0 1 4 0Z" /></Icon>,
  pkg: (p) => <Icon {...p}><path d="m21 8-9-5-9 5v8l9 5 9-5V8Z" /><path d="m3 8 9 5 9-5M12 13v9" /></Icon>,
  alert: (p) => <Icon {...p}><path d="M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0Z" /><path d="M12 9v4M12 17h.01" /></Icon>,
  trendUp: (p) => <Icon {...p}><path d="M22 7 13.5 15.5l-5-5L2 17" /><path d="M16 7h6v6" /></Icon>,
  trendDown: (p) => <Icon {...p}><path d="M22 17 13.5 8.5l-5 5L2 7" /><path d="M16 17h6v-6" /></Icon>,
  clock: (p) => <Icon {...p}><circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 2" /></Icon>,
  flask: (p) => <Icon {...p}><path d="M9 3h6M10 3v6.5L4.5 19a1.5 1.5 0 0 0 1.3 2.3h12.4A1.5 1.5 0 0 0 19.5 19L14 9.5V3M7.5 14h9" /></Icon>,
  user: (p) => <Icon {...p}><circle cx="12" cy="8" r="4" /><path d="M6 21v-2a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v2" /></Icon>,
  settings: (p) => <Icon {...p}><circle cx="12" cy="12" r="3" /><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1Z" /></Icon>,
  logout: (p) => <Icon {...p}><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9" /></Icon>,
  play: (p) => <Icon {...p}><path d="m6 4 14 8-14 8V4Z" /></Icon>,
  message: (p) => <Icon {...p}><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2Z" /></Icon>,
  external: (p) => <Icon {...p}><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14 21 3" /></Icon>,
  expedite: (p) => <Icon {...p}><path d="M13 2 3 14h9l-1 8 10-12h-9l1-8Z" /></Icon>,
  swap: (p) => <Icon {...p}><path d="M16 3h5v5M21 3l-7 7M8 21H3v-5M3 21l7-7" /></Icon>,
};

/* Terrace four-peak glyph — the only ornamental mark, currentColor-aware */
function Glyph({ size = 16, stroke = 1.6 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 68 56" fill="none" stroke="currentColor"
      strokeWidth={stroke} strokeLinejoin="round" strokeLinecap="round" style={{ flexShrink: 0 }}>
      <path d="M28 10 L34 4 L40 10" /><path d="M20 22 L34 12 L48 22" />
      <path d="M11 35 L34 17 L57 35" /><path d="M3 48 L34 28 L65 48" />
    </svg>
  );
}

function TerraceLogo({ height = 30 }) {
  const w = (height * 267) / 62;
  return (
    <svg viewBox="0 0 267 62" width={w} height={height} role="img" aria-label="Terrace" style={{ display: "block" }}>
      <g transform="translate(-8.8 10.22) scale(0.8)" fill="none" stroke="currentColor" strokeWidth={3.4} strokeLinejoin="round" strokeLinecap="round">
        <path d="M44 16 L50 10 L56 16" /><path d="M36 28 L50 18 L64 28" /><path d="M26 42 L50 28 L74 42" /><path d="M16 56 L50 40 L84 56" />
      </g>
      <text x="74" y="40" fontFamily="var(--font-sans)" fontSize="30" fontWeight={600} fill="currentColor" letterSpacing="6.6">TERRACE</text>
      <line x1="74" y1="55" x2="252" y2="55" stroke="var(--clay)" strokeWidth="2" />
    </svg>
  );
}

/* ---------- Avatar ---------- */
function Avatar({ initials, size = "md", clay, org }) {
  return <span className={cx("avatar", size, clay && "clay", org && "org")}>{initials || "?"}</span>;
}

/* ---------- Format badge ---------- */
function FormatBadge({ format, showLabel = true }) {
  const f = D.FORMAT[format];
  const gl = format === "hospital" ? <Icons.cross size={11} /> : format === "flagship" ? <Icons.store size={11} /> : <Icons.mapPin size={11} />;
  return <span className={cx("fmt", format)}><span className="gl">{gl}</span>{showLabel && f.short}</span>;
}

/* ---------- Health pill ---------- */
function HealthPill({ status }) {
  const h = D.HEALTH[status];
  const tone = { healthy: "var(--green)", watch: "var(--amber)", atrisk: "var(--red)", critical: "var(--clay)" }[status];
  const bg = { healthy: "var(--green-wash)", watch: "var(--amber-wash)", atrisk: "var(--red-wash)", critical: "var(--clay-wash)" }[status];
  const fg = { healthy: "var(--green)", watch: "var(--amber)", atrisk: "var(--red)", critical: "var(--clay-deep)" }[status];
  return <span className="hpill" style={{ background: bg, color: fg }}><span className="dot" style={{ background: tone }} />{h.label}</span>;
}

/* ---------- Provenance "from Terrace" ---------- */
function Prov({ children = "from Terrace", muted }) {
  return <span className={cx("prov", muted && "muted")}><span className="gl"><Glyph size={12} /></span>{children}</span>;
}

/* ---------- money (INR, Indian grouping) ---------- */
function inr(n) { return "₹" + Number(n).toLocaleString("en-IN", { maximumFractionDigits: 0 }); }

/* ---------- SKU label ---------- */
function skuName(key) { return D.SKU[key] ? D.SKU[key].name : key; }

/* ---------- date helpers ---------- */
const MO = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const WD = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const MOFULL = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
function parseDate(s) { return new Date(s + "T00:00:00"); }
function shortDate(s) { const d = parseDate(s); return `${MO[d.getMonth()]} ${d.getDate()}`; }
function longDate(s) { const d = parseDate(s); return `${WD[d.getDay()]}, ${MOFULL[d.getMonth()]} ${d.getDate()}`; }

/* ---------- Drawer ---------- */
function Drawer({ open, onClose, title, children, footer, width = 480 }) {
  useEffect(() => {
    function esc(e) { if (e.key === "Escape") onClose(); }
    if (open) window.addEventListener("keydown", esc);
    return () => window.removeEventListener("keydown", esc);
  }, [open, onClose]);
  return (
    <React.Fragment>
      <div className={cx("scrim", open && "show")} style={{ pointerEvents: open ? "auto" : "none" }} onClick={onClose} />
      <aside className={cx("drawer", open && "show")} style={{ width: `min(${width}px, 96vw)` }} aria-hidden={!open}>
        {open && (
          <React.Fragment>
            <div className="drawer-head">
              <span className="dt">{title}</span>
              <button className="iconbtn" onClick={onClose} aria-label="Close"><Icons.close size={16} /></button>
            </div>
            <div className="drawer-body">{children}</div>
            {footer && <div className="drawer-foot">{footer}</div>}
          </React.Fragment>
        )}
      </aside>
    </React.Fragment>
  );
}

function useClickOutside(ref, onOut) {
  useEffect(() => {
    function h(e) { if (ref.current && !ref.current.contains(e.target)) onOut(); }
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, [onOut]);
}

function SectionHead({ title, count, action }) {
  return (
    <div className="section-head">
      <h2>{title}</h2>
      {count != null && <span className="ct">{count}</span>}
      <span className="rule" />
      {action}
    </div>
  );
}

Object.assign(window, {
  cx, Icon, Icons, Glyph, TerraceLogo, Avatar, FormatBadge, HealthPill, Prov,
  inr, skuName, parseDate, shortDate, longDate,
  Drawer, useClickOutside, SectionHead,
});
