/* global React */
// Shared UI primitives for VakeelOS mobile.
// Editorial · calm · numbered. Em dashes welcome.

const { useState, useRef, useEffect, useLayoutEffect, createContext, useContext } = React;

// ───────────────────────────────────────── Status pill
function Pill({ tone = "neutral", children, dot = false, soft = false }) {
  const tones = {
    neutral: { bg: soft ? "rgba(22,21,20,0.05)" : "transparent", fg: "var(--ink-2)", dot: "var(--ink-3)", border: "var(--rule)" },
    live:    { bg: "rgba(28,82,53,0.07)",  fg: "var(--green-ink)", dot: "var(--green)", border: "rgba(28,82,53,0.18)" },
    blue:    { bg: "rgba(24,49,107,0.06)", fg: "var(--blue-ink)",  dot: "var(--blue)",  border: "rgba(24,49,107,0.18)" },
    gold:    { bg: "rgba(168,126,42,0.08)", fg: "var(--gold-ink)", dot: "var(--gold)",  border: "rgba(168,126,42,0.22)" },
    red:     { bg: "rgba(140,32,32,0.06)", fg: "var(--red-ink)",   dot: "var(--red)",   border: "rgba(140,32,32,0.20)" },
    orange:  { bg: "rgba(176,86,12,0.07)", fg: "var(--orange-ink)",dot: "var(--orange)",border: "rgba(176,86,12,0.20)" },
    purple:  { bg: "rgba(86,52,140,0.06)", fg: "var(--purple-ink)",dot: "var(--purple)",border: "rgba(86,52,140,0.20)" },
    teal:    { bg: "rgba(28,82,82,0.06)",  fg: "var(--teal-ink)",  dot: "var(--teal)",  border: "rgba(28,82,82,0.18)" },
    ink:     { bg: "var(--ink)", fg: "var(--paper)", dot: "var(--gold)", border: "transparent" },
  };
  const t = tones[tone] || tones.neutral;
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6,
      padding: "2px 8px", borderRadius: 999,
      background: t.bg, color: t.fg,
      border: `1px solid ${t.border}`,
      fontSize: 11, fontWeight: 500, letterSpacing: 0.2,
      fontFamily: "var(--sans)",
      whiteSpace: "nowrap",
    }}>
      {dot && <span style={{ width: 5, height: 5, borderRadius: 999, background: t.dot }} />}
      {children}
    </span>
  );
}

// ───────────────────────────────────────── Section eyebrow ("00 — Section")
function Eyebrow({ index, children, align = "left" }) {
  return (
    <div style={{
      display: "flex", alignItems: "baseline", gap: 10,
      justifyContent: align === "left" ? "flex-start" : align,
      fontFamily: "var(--sans)",
      fontSize: 11, letterSpacing: 1.4, textTransform: "uppercase",
      color: "var(--ink-3)", fontWeight: 500,
    }}>
      {index != null && <span style={{ fontFamily: "var(--mono)", fontVariantNumeric: "tabular-nums", color: "var(--ink-2)" }}>{String(index).padStart(2, "0")}</span>}
      {index != null && <span style={{ flex: "0 0 14px", height: 1, background: "var(--rule)", alignSelf: "center" }} />}
      <span>{children}</span>
    </div>
  );
}

// ───────────────────────────────────────── Hairline divider
function Rule({ inset = 0, dim = false }) {
  return <div style={{ height: 1, background: dim ? "var(--rule-soft)" : "var(--rule)", marginLeft: inset, marginRight: inset }} />;
}

// ───────────────────────────────────────── Tap target / Button
function Btn({ variant = "primary", children, onClick, size = "md", icon, iconRight, style = {}, full = false, disabled = false, tone }) {
  const sizes = {
    sm: { h: 32, px: 10, fs: 13 },
    md: { h: 40, px: 14, fs: 14 },
    lg: { h: 48, px: 18, fs: 15 },
  }[size];
  const variants = {
    primary: { bg: "var(--ink)", fg: "var(--paper)", border: "var(--ink)" },
    secondary: { bg: "var(--paper)", fg: "var(--ink)", border: "var(--ink)" },
    ghost: { bg: "transparent", fg: "var(--ink-2)", border: "transparent" },
    quiet: { bg: "var(--card)", fg: "var(--ink)", border: "var(--rule)" },
    gold: { bg: "var(--gold)", fg: "#1a1300", border: "var(--gold)" },
    danger: { bg: "var(--paper)", fg: "var(--red-ink)", border: "rgba(140,32,32,0.3)" },
  };
  const v = variants[variant] || variants.primary;
  return (
    <button onClick={onClick} disabled={disabled} style={{
      height: sizes.h,
      padding: `0 ${sizes.px}px`,
      borderRadius: variant === "ghost" ? 6 : 999,
      background: v.bg, color: v.fg,
      border: `1px solid ${v.border}`,
      fontSize: sizes.fs, fontWeight: 500,
      fontFamily: "var(--sans)",
      display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8,
      cursor: disabled ? "not-allowed" : "pointer",
      opacity: disabled ? 0.5 : 1,
      width: full ? "100%" : "auto",
      letterSpacing: 0.1,
      transition: "transform 80ms ease, background 120ms ease",
      ...style,
    }}
      onMouseDown={(e) => e.currentTarget.style.transform = "scale(0.98)"}
      onMouseUp={(e) => e.currentTarget.style.transform = "scale(1)"}
      onMouseLeave={(e) => e.currentTarget.style.transform = "scale(1)"}
    >
      {icon}
      {children}
      {iconRight}
    </button>
  );
}

// ───────────────────────────────────────── Card
function Card({ children, style = {}, padded = true, onClick, accent }) {
  return (
    <div onClick={onClick} style={{
      background: "var(--card)",
      border: "1px solid var(--rule)",
      borderRadius: 14,
      padding: padded ? 16 : 0,
      position: "relative",
      overflow: "hidden",
      cursor: onClick ? "pointer" : "default",
      ...style,
    }}>
      {accent && <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: 2, background: accent }} />}
      {children}
    </div>
  );
}

// ───────────────────────────────────────── Numeric meta line ("APHC · Court 12 · 11:00")
function MetaLine({ items, sep = "·", style = {} }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 6, color: "var(--ink-3)", fontSize: 12.5, fontFamily: "var(--sans)", lineHeight: 1.4, flexWrap: "wrap", ...style }}>
      {items.filter(Boolean).map((it, i) => (
        <React.Fragment key={i}>
          {i > 0 && <span style={{ opacity: 0.4, whiteSpace: "nowrap" }}>{sep}</span>}
          <span style={{ whiteSpace: "nowrap" }}>{it}</span>
        </React.Fragment>
      ))}
    </div>
  );
}

// ───────────────────────────────────────── Icons (lucide-style mini SVGs, 1px stroke)
const I = ({ d, size = 18, fill, stroke = "currentColor", sw = 1.6, viewBox = "0 0 24 24" }) => (
  <svg width={size} height={size} viewBox={viewBox} fill={fill || "none"} stroke={stroke} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round">
    {typeof d === "string" ? <path d={d} /> : d}
  </svg>
);
const Icons = {
  home: (p) => <I {...p} d="M3 11l9-8 9 8M5 10v10h14V10" />,
  cases: (p) => <I {...p} d="M4 7h16v13H4zM9 7V5a2 2 0 012-2h2a2 2 0 012 2v2" />,
  causelist: (p) => <I {...p} d={<><line x1="8" y1="6" x2="20" y2="6"/><line x1="8" y1="12" x2="20" y2="12"/><line x1="8" y1="18" x2="20" y2="18"/><circle cx="4" cy="6" r="1" fill="currentColor"/><circle cx="4" cy="12" r="1" fill="currentColor"/><circle cx="4" cy="18" r="1" fill="currentColor"/></>} />,
  more: (p) => <I {...p} d={<><circle cx="5" cy="12" r="1.2" fill="currentColor"/><circle cx="12" cy="12" r="1.2" fill="currentColor"/><circle cx="19" cy="12" r="1.2" fill="currentColor"/></>} />,
  search: (p) => <I {...p} d={<><circle cx="11" cy="11" r="7"/><line x1="20" y1="20" x2="16.5" y2="16.5"/></>} />,
  bell: (p) => <I {...p} d="M6 8a6 6 0 0112 0v4l1.5 3h-15L6 12V8zM10 19a2 2 0 004 0" />,
  user: (p) => <I {...p} d={<><circle cx="12" cy="8" r="4"/><path d="M4 21c1-4 4-6 8-6s7 2 8 6"/></>} />,
  mic: (p) => <I {...p} d="M12 3a3 3 0 00-3 3v6a3 3 0 006 0V6a3 3 0 00-3-3zM5 11a7 7 0 0014 0M12 18v3" />,
  plus: (p) => <I {...p} d={<><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></>} />,
  arrowRight: (p) => <I {...p} d="M5 12h14M13 6l6 6-6 6" />,
  arrowLeft: (p) => <I {...p} d="M19 12H5M11 6l-6 6 6 6" />,
  chevR: (p) => <I {...p} d="M9 6l6 6-6 6" />,
  chevL: (p) => <I {...p} d="M15 6l-6 6 6 6" />,
  chevD: (p) => <I {...p} d="M6 9l6 6 6-6" />,
  close: (p) => <I {...p} d="M6 6l12 12M6 18L18 6" />,
  refresh: (p) => <I {...p} d="M21 12a9 9 0 11-3-6.7M21 4v5h-5" />,
  gavel: (p) => <I {...p} d="M14 4l6 6M11 7l6 6-4 4-6-6 4-4zM3 21h12" />,
  scale: (p) => <I {...p} d="M12 4v16M6 8h12M5 8l-3 6h6l-3-6zM19 8l-3 6h6l-3-6z" />,
  doc: (p) => <I {...p} d="M14 3H6v18h12V7l-4-4zM14 3v4h4M9 13h6M9 17h4" />,
  clock: (p) => <I {...p} d={<><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></>} />,
  calendar: (p) => <I {...p} d={<><rect x="3" y="5" width="18" height="16" rx="2"/><line x1="3" y1="10" x2="21" y2="10"/><line x1="8" y1="3" x2="8" y2="7"/><line x1="16" y1="3" x2="16" y2="7"/></>} />,
  check: (p) => <I {...p} d="M5 12l5 5L20 6" />,
  filter: (p) => <I {...p} d="M3 5h18l-7 9v6l-4-2v-4L3 5z" />,
  edit: (p) => <I {...p} d="M4 20h4l10-10-4-4L4 16v4zM14 6l4 4" />,
  share: (p) => <I {...p} d={<><circle cx="6" cy="12" r="3"/><circle cx="18" cy="6" r="3"/><circle cx="18" cy="18" r="3"/><line x1="8.5" y1="10.5" x2="15.5" y2="7"/><line x1="8.5" y1="13.5" x2="15.5" y2="17"/></>} />,
  whatsapp: (p) => <I {...p} d="M3.5 20.5l1.4-4.6A8.5 8.5 0 1112.5 21a8.4 8.4 0 01-4.2-1.1l-4.8.6zM8 10c0 4 3 6.5 5.5 7 .5.1 1 0 1.5-.3l1-.7c.3-.2.7-.2 1 0l1.5 1c.3.2.4.6.2.9-.6.9-1.6 1.6-2.7 1.6-3.8 0-7-3.2-7-7 0-1.1.7-2 1.5-2.6.3-.2.7-.2.9.1l1 1.5c.2.3.2.7 0 1l-.7 1c-.3.5-.3 1.1-.2 1.5z" />,
  ai: (p) => <I {...p} d="M12 3l1.5 4L18 8.5 13.5 10 12 14l-1.5-4L6 8.5 10.5 7 12 3zM18 14l.8 2 2 .8-2 .8-.8 2-.8-2-2-.8 2-.8.8-2zM5 16l.6 1.6 1.6.6-1.6.6L5 20.4l-.6-1.6L2.8 18.2 4.4 17.6 5 16z" />,
  paperclip: (p) => <I {...p} d="M21 12L12 21a5 5 0 01-7-7L14 5a3.5 3.5 0 015 5l-9 9a2 2 0 01-3-3l8.5-8.5" />,
  send: (p) => <I {...p} d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z" />,
  camera: (p) => <I {...p} d={<><path d="M3 7h4l2-3h6l2 3h4v13H3z"/><circle cx="12" cy="13" r="4"/></>} />,
  pin: (p) => <I {...p} d="M12 2v8m0 0l-5 5h10l-5-5zM12 15v6" />,
  download: (p) => <I {...p} d="M12 3v13m0 0l-5-5m5 5l5-5M5 21h14" />,
  trash: (p) => <I {...p} d="M4 6h16M6 6l1 14h10l1-14M10 11v6M14 11v6M9 6V4h6v2" />,
  archive: (p) => <I {...p} d="M3 4h18v4H3zM5 8h14v12H5zM10 12h4" />,
  shield: (p) => <I {...p} d="M12 3l8 3v5c0 5-4 9-8 10-4-1-8-5-8-10V6l8-3z" />,
  bolt: (p) => <I {...p} d="M13 2L4 14h7l-1 8 9-12h-7l1-8z" />,
  inr: (p) => <I {...p} d="M7 5h10M7 9h10M7 5c4 0 6 2 6 5s-2 5-6 5h-1l7 6" />,
  briefcase: (p) => <I {...p} d="M3 8h18v12H3zM9 8V5a2 2 0 012-2h2a2 2 0 012 2v3" />,
  building: (p) => <I {...p} d="M4 21V5l8-3 8 3v16M9 9h2M13 9h2M9 13h2M13 13h2M9 17h2M13 17h2" />,
  flame: (p) => <I {...p} d="M12 3c2 4 6 6 6 11a6 6 0 11-12 0c0-3 2-5 3-7 1 2 3 0 3-4z" />,
  bookmark: (p) => <I {...p} d="M6 3h12v18l-6-4-6 4z" />,
  pause: (p) => <I {...p} d="M8 5v14M16 5v14" />,
  play: (p) => <I {...p} d="M6 4l14 8-14 8V4z" />,
  stop: (p) => <I {...p} d="M5 5h14v14H5z" />,
  sparkle: (p) => <I {...p} d="M12 3v18M3 12h18M6 6l12 12M18 6L6 18" sw={0.8} />,
  globe: (p) => <I {...p} d={<><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c3 3 3 15 0 18M12 3c-3 3-3 15 0 18"/></>} />,
};

// ───────────────────────────────────────── Avatar (initials, no image)
function Avatar({ name = "Vikky Cumba", size = 36, tone = "ink" }) {
  const initials = name.split(" ").filter(Boolean).slice(0, 2).map(s => s[0]).join("").toUpperCase();
  const tones = {
    ink:   { bg: "var(--ink)",  fg: "var(--paper)" },
    paper: { bg: "var(--paper)", fg: "var(--ink)", border: "1px solid var(--rule)" },
    gold:  { bg: "var(--gold)", fg: "#1a1300" },
  };
  const t = tones[tone] || tones.ink;
  return (
    <div style={{
      width: size, height: size, borderRadius: 999,
      background: t.bg, color: t.fg, border: t.border || "none",
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      fontFamily: "var(--sans)", fontWeight: 500, fontSize: size * 0.36, letterSpacing: 0.5,
      flexShrink: 0,
    }}>{initials}</div>
  );
}

// ───────────────────────────────────────── Screen frame (top nav, body)
function Screen({ children, header, scroll = true, padBottom = 100, style = {} }) {
  return (
    <div style={{
      position: "relative",
      flex: 1,
      minHeight: 0,
      background: "var(--paper)",
      display: "flex", flexDirection: "column",
      ...style,
    }}>
      {header}
      <div style={{
        flex: 1,
        overflowY: scroll ? "auto" : "hidden",
        overflowX: "hidden",
        WebkitOverflowScrolling: "touch",
        paddingBottom: padBottom,
      }}>
        {children}
      </div>
    </div>
  );
}

// ───────────────────────────────────────── Status bar (faux iOS)
function StatusBar({ light = false }) {
  return (
    <div style={{
      height: 72, paddingTop: 28, paddingLeft: 24, paddingRight: 24,
      display: "flex", alignItems: "center", justifyContent: "space-between",
      color: light ? "var(--paper)" : "var(--ink)",
      fontFamily: "var(--sans)", fontWeight: 600, fontSize: 14,
      flexShrink: 0,
      fontVariantNumeric: "tabular-nums",
    }}>
      <span>9:41</span>
      <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
        {/* signal */}
        <svg width="17" height="11" viewBox="0 0 17 11"><g fill={light ? "currentColor" : "currentColor"}><rect x="0" y="7" width="3" height="4" rx="0.5"/><rect x="4.5" y="5" width="3" height="6" rx="0.5"/><rect x="9" y="3" width="3" height="8" rx="0.5"/><rect x="13.5" y="0" width="3" height="11" rx="0.5"/></g></svg>
        {/* wifi */}
        <svg width="15" height="11" viewBox="0 0 15 11"><path d="M7.5 0C4.7 0 2.1 1 0 2.8L7.5 11 15 2.8C12.9 1 10.3 0 7.5 0z" fill="currentColor" opacity="0.95"/></svg>
        {/* battery */}
        <svg width="25" height="11" viewBox="0 0 25 11"><rect x="0.5" y="0.5" width="21" height="10" rx="2.5" fill="none" stroke="currentColor" opacity="0.5"/><rect x="22.5" y="3.5" width="1.5" height="4" rx="0.5" fill="currentColor" opacity="0.5"/><rect x="2" y="2" width="18" height="7" rx="1.5" fill="currentColor"/></svg>
      </div>
    </div>
  );
}

// ───────────────────────────────────────── Top app bar
function TopBar({ title, eyebrow, back, right, large = false, transparent = false, sub }) {
  return (
    <div style={{
      paddingLeft: 20, paddingRight: 20, paddingTop: 10, paddingBottom: large ? 12 : 14,
      background: transparent ? "transparent" : "var(--paper)",
      borderBottom: large ? "none" : "1px solid var(--rule-soft)",
      flexShrink: 0,
    }}>
      <div style={{ height: 36, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6, minWidth: 0 }}>
          {back && (
            <button onClick={back} style={{
              width: 36, height: 36, marginLeft: -8, marginRight: 4, borderRadius: 999,
              background: "transparent", border: "none", color: "var(--ink)",
              display: "inline-flex", alignItems: "center", justifyContent: "center", cursor: "pointer",
            }}><Icons.chevL size={22} /></button>
          )}
          {!large && (
            <div style={{ display: "flex", flexDirection: "column", minWidth: 0 }}>
              {eyebrow && <span style={{ fontSize: 10.5, letterSpacing: 1.2, textTransform: "uppercase", color: "var(--ink-3)", fontFamily: "var(--sans)" }}>{eyebrow}</span>}
              <span style={{ fontFamily: "var(--sans)", fontSize: 17, fontWeight: 600, color: "var(--ink)", letterSpacing: -0.3, lineHeight: 1.1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{title}</span>
            </div>
          )}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>{right}</div>
      </div>
      {large && (
        <div style={{ marginTop: 8 }}>
          {eyebrow && <div style={{ fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: 2.2, textTransform: "uppercase", color: "var(--ink-3)", fontWeight: 500 }}>{eyebrow}</div>}
          <h1 style={{ fontFamily: "var(--serif)", fontWeight: 400, fontSize: 34, lineHeight: 1.08, letterSpacing: -0.9, color: "var(--ink)", margin: "6px 0 0 0", textWrap: "balance" }}>{title}</h1>
          {sub && <div style={{ marginTop: 6, fontFamily: "var(--sans)", fontSize: 13.5, color: "var(--ink-2)" }}>{sub}</div>}
        </div>
      )}
    </div>
  );
}

// ───────────────────────────────────────── Bottom tab bar
function TabBar({ current, onChange }) {
  const tabs = [
    { id: "today",     label: "Today",     icon: Icons.home },
    { id: "cases",     label: "Cases",     icon: Icons.cases },
    { id: "causelist", label: "Causelist", icon: Icons.causelist },
    { id: "more",      label: "More",      icon: Icons.more },
  ];
  return (
    <div style={{
      position: "absolute", left: 0, right: 0, bottom: 0,
      paddingBottom: 18, paddingTop: 8, paddingLeft: 8, paddingRight: 8,
      background: "color-mix(in oklab, var(--paper) 88%, transparent)",
      backdropFilter: "blur(18px) saturate(140%)",
      WebkitBackdropFilter: "blur(18px) saturate(140%)",
      borderTop: "1px solid var(--rule-soft)",
      display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 4,
      zIndex: 50,
    }}>
      {tabs.map(t => {
        const Active = t.icon;
        const isActive = current === t.id;
        return (
          <button key={t.id} onClick={() => onChange(t.id)} style={{
            background: "transparent", border: "none",
            display: "flex", flexDirection: "column", alignItems: "center", gap: 3,
            paddingTop: 6, paddingBottom: 4,
            color: isActive ? "var(--ink)" : "var(--ink-3)",
            cursor: "pointer",
            fontFamily: "var(--sans)",
          }}>
            <Active size={22} sw={isActive ? 1.8 : 1.5} />
            <span style={{ fontSize: 10.5, fontWeight: isActive ? 500 : 400, letterSpacing: 0.2 }}>{t.label}</span>
          </button>
        );
      })}
    </div>
  );
}

// ───────────────────────────────────────── List item (iOS-grouped row)
function Row({ leading, title, sub, trailing, onClick, children, dense = false }) {
  return (
    <div onClick={onClick} style={{
      padding: dense ? "10px 16px" : "14px 16px",
      display: "flex", alignItems: "center", gap: 12,
      cursor: onClick ? "pointer" : "default",
    }}>
      {leading && <div style={{ flexShrink: 0 }}>{leading}</div>}
      <div style={{ flex: 1, minWidth: 0 }}>
        {title && <div style={{ fontFamily: "var(--sans)", fontSize: 15, color: "var(--ink)", fontWeight: 500, lineHeight: 1.35, overflow: "hidden", textOverflow: "ellipsis" }}>{title}</div>}
        {sub && <div style={{ fontFamily: "var(--sans)", fontSize: 12.5, color: "var(--ink-3)", marginTop: 2, lineHeight: 1.4 }}>{sub}</div>}
        {children}
      </div>
      {trailing && <div style={{ flexShrink: 0, color: "var(--ink-3)" }}>{trailing}</div>}
    </div>
  );
}

// ───────────────────────────────────────── Tappable / press feedback
function Tap({ children, onClick, style = {} }) {
  const [down, setDown] = useState(false);
  return (
    <div onPointerDown={() => setDown(true)} onPointerUp={() => setDown(false)} onPointerLeave={() => setDown(false)}
      onClick={onClick}
      style={{ cursor: onClick ? "pointer" : "default", transition: "opacity 80ms", opacity: down ? 0.6 : 1, ...style }}>
      {children}
    </div>
  );
}

// Export to window
Object.assign(window, {
  Pill, Eyebrow, Rule, Btn, Card, MetaLine, Icons, Avatar,
  Screen, StatusBar, TopBar, TabBar, Row, Tap,
});
