"use client";
/** macOS-style component kit, themed with Brand Tempest tokens. */
import { createContext, forwardRef, useCallback, useContext, useEffect, useRef, useState, type ButtonHTMLAttributes, type InputHTMLAttributes, type ReactNode, type SelectHTMLAttributes, type TextareaHTMLAttributes } from "react";
import { createPortal } from "react-dom";
import clsx from "clsx";
import { Check, ChevronDown, Info, Loader2, X, AlertTriangle, CheckCircle2 } from "lucide-react";

export const cx = clsx;

/* ---------------- Button ---------------- */
type BtnProps = ButtonHTMLAttributes<HTMLButtonElement> & { variant?: "primary" | "secondary" | "ghost" | "danger" | "tinted"; size?: "sm" | "md" | "lg"; loading?: boolean; icon?: ReactNode };
export const Button = forwardRef<HTMLButtonElement, BtnProps>(function Button({ variant = "secondary", size = "md", loading, icon, className, children, disabled, ...rest }, ref) {
  return (
    <button ref={ref} disabled={disabled || loading} {...rest}
      className={cx("inline-flex select-none items-center justify-center gap-1.5 whitespace-nowrap rounded-[12px] font-medium transition-all duration-200 active:scale-[.97] disabled:pointer-events-none disabled:opacity-50",
        size === "sm" && "h-8 px-3 text-[12px]", size === "md" && "h-9 px-3.5 text-[13px]", size === "lg" && "h-11 px-5 text-[14px]",
        variant === "primary" && "bg-gradient-to-b from-[#3B76FF] to-brand-600 text-white shadow-[0_1px_0_rgb(255_255_255/.25)_inset,0_10px_22px_-10px_rgb(var(--brand)/.8)] hover:-translate-y-px hover:shadow-[0_1px_0_rgb(255_255_255/.25)_inset,0_14px_26px_-10px_rgb(var(--brand)/.9)]",
        variant === "secondary" && "border border-white/80 bg-white/70 text-ink shadow-[0_2px_8px_-4px_rgb(15_23_42/.15)] backdrop-blur hover:bg-white dark:border-white/10 dark:bg-white/5 dark:hover:bg-white/10",
        variant === "ghost" && "text-ink-2 hover:bg-ink/[.06] hover:text-ink",
        variant === "tinted" && "bg-brand/10 text-brand hover:bg-brand/15",
        variant === "danger" && "bg-bad text-white hover:brightness-110", className)}>
      {loading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : icon}
      {children}
    </button>
  );
});

/* ---------------- Inputs ---------------- */
export const Input = forwardRef<HTMLInputElement, InputHTMLAttributes<HTMLInputElement>>(function Input({ className, ...p }, ref) {
  return <input ref={ref} className={cx("field", className)} {...p} />;
});
export const Textarea = forwardRef<HTMLTextAreaElement, TextareaHTMLAttributes<HTMLTextAreaElement>>(function Textarea({ className, ...p }, ref) {
  return <textarea ref={ref} className={cx("field min-h-[80px] resize-y leading-relaxed", className)} {...p} />;
});
export function Select({ className, children, ...p }: SelectHTMLAttributes<HTMLSelectElement>) {
  return (
    <div className={cx("relative", className)}>
      <select className="field appearance-none pr-7" {...p}>{children}</select>
      <ChevronDown className="pointer-events-none absolute right-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-ink-3" />
    </div>
  );
}
export function Field({ label, hint, error, children, className }: { label?: ReactNode; hint?: ReactNode; error?: string | null; children: ReactNode; className?: string }) {
  return (
    <label className={cx("block space-y-1", className)}>
      {label && <span className="label block">{label}</span>}
      {children}
      {error ? <span className="block text-[11.5px] text-bad">{error}</span> : hint ? <span className="block text-[11.5px] text-ink-3">{hint}</span> : null}
    </label>
  );
}

/** iOS/macOS switch */
export function Toggle({ checked, onChange, label, disabled }: { checked: boolean; onChange: (v: boolean) => void; label?: ReactNode; disabled?: boolean }) {
  return (
    <label className={cx("inline-flex cursor-pointer items-center gap-2", disabled && "opacity-50")}>
      <button type="button" role="switch" aria-checked={checked} disabled={disabled} onClick={() => onChange(!checked)}
        className={cx("relative h-[20px] w-[34px] shrink-0 rounded-full transition-colors", checked ? "bg-brand" : "bg-ink/20")}>
        <span className={cx("absolute top-[2px] h-4 w-4 rounded-full bg-white shadow transition-transform", checked ? "translate-x-[16px]" : "translate-x-[2px]")} />
      </button>
      {label && <span className="text-[13px]">{label}</span>}
    </label>
  );
}

export function Checkbox({ checked, onChange, label }: { checked: boolean; onChange: (v: boolean) => void; label?: ReactNode }) {
  return (
    <label className="inline-flex cursor-pointer items-center gap-2 text-[13px]">
      <span onClick={(e) => { e.preventDefault(); onChange(!checked); }} className={cx("grid h-4 w-4 place-items-center rounded-[4px] border transition", checked ? "border-brand bg-brand text-white" : "border-ink/25 bg-panel")}>
        {checked && <Check className="h-3 w-3" strokeWidth={3} />}
      </span>
      {label}
    </label>
  );
}

/** macOS segmented control */
export function Segmented<T extends string>({ value, onChange, options, size = "md" }: { value: T; onChange: (v: T) => void; options: { value: T; label: ReactNode }[]; size?: "sm" | "md" }) {
  return (
    <div className="inline-flex rounded-[8px] bg-ink/[.06] p-[2px]">
      {options.map((o) => (
        <button key={o.value} type="button" onClick={() => onChange(o.value)}
          className={cx("rounded-[6px] font-medium transition", size === "sm" ? "px-2 py-0.5 text-[11.5px]" : "px-3 py-1 text-[12.5px]",
            value === o.value ? "bg-panel text-ink shadow-[0_1px_2px_rgb(0_0_0/.12),0_0_0_.5px_rgb(0_0_0/.06)]" : "text-ink-2 hover:text-ink")}>
          {o.label}
        </button>
      ))}
    </div>
  );
}

/* ---------------- Display ---------------- */
const TONES: Record<string, string> = {
  gray: "bg-ink/[.07] text-ink-2", red: "bg-brand/10 text-brand", green: "bg-ok/12 text-ok", amber: "bg-warn/15 text-warn",
  blue: "bg-info/10 text-info", violet: "bg-violet/12 text-violet",
};
export function Badge({ tone = "gray", children, className, dot }: { tone?: keyof typeof TONES | string; children: ReactNode; className?: string; dot?: boolean }) {
  return (
    <span className={cx("inline-flex items-center gap-1 whitespace-nowrap rounded-full px-2 py-[1px] text-[11px] font-medium", TONES[tone] ?? TONES.gray, className)}>
      {dot && <span className="h-1.5 w-1.5 rounded-full bg-current" />}{children}
    </span>
  );
}

export function Card({ title, actions, children, className, bodyClass, subtitle }: { title?: ReactNode; subtitle?: ReactNode; actions?: ReactNode; children: ReactNode; className?: string; bodyClass?: string }) {
  return (
    <section className={cx("card", className)}>
      {(title || actions) && (
        <header className="flex items-center justify-between gap-3 px-5 pb-1 pt-4">
          <div className="min-w-0"><h3 className="truncate font-display text-[15px] font-bold tracking-tight">{title}</h3>{subtitle && <p className="truncate text-[12px] text-ink-3">{subtitle}</p>}</div>
          {actions && <div className="flex shrink-0 items-center gap-1.5">{actions}</div>}
        </header>
      )}
      <div className={cx("p-5 pt-3", bodyClass)}>{children}</div>
    </section>
  );
}

export function Stat({ label, value, sub, tone, icon }: { label: string; value: ReactNode; sub?: ReactNode; tone?: "up" | "down" | null; icon?: ReactNode }) {
  return (
    <div className="card lift px-5 py-4">
      <div className="flex items-center justify-between text-[12px] font-medium text-ink-2">{label}{icon && <span className="grid h-8 w-8 place-items-center rounded-full bg-brand/10 text-brand [&>svg]:!text-brand">{icon}</span>}</div>
      <div className="mt-2 font-display text-[28px] font-bold leading-tight tracking-tight">{value}</div>
      {sub && <div className={cx("mt-1 inline-flex rounded-full px-2 py-0.5 text-[11.5px] font-medium", tone === "up" ? "bg-ok/10 text-ok" : tone === "down" ? "bg-bad/10 text-bad" : "text-ink-3")}>{sub}</div>}
    </div>
  );
}

export function Empty({ icon, title, children, action }: { icon?: ReactNode; title: string; children?: ReactNode; action?: ReactNode }) {
  return (
    <div className="flex flex-col items-center justify-center px-6 py-14 text-center">
      {icon && <div className="mb-3 grid h-12 w-12 place-items-center rounded-2xl bg-ink/[.05] text-ink-3">{icon}</div>}
      <p className="font-medium">{title}</p>
      {children && <p className="mt-1 max-w-sm text-[12.5px] text-ink-3">{children}</p>}
      {action && <div className="mt-4">{action}</div>}
    </div>
  );
}

export function Avatar({ name, size = 28, className }: { name: string; size?: number; className?: string }) {
  const initials = name.split(/\s+/).filter(Boolean).slice(0, 2).map((p) => p[0]!.toUpperCase()).join("") || "?";
  let h = 0;
  for (const c of name) h = (h * 31 + c.charCodeAt(0)) % 360;
  return (
    <span className={cx("inline-grid shrink-0 place-items-center rounded-full font-semibold text-white", className)} style={{ width: size, height: size, fontSize: size * 0.38, background: `linear-gradient(160deg, hsl(${h} 55% 58%), hsl(${(h + 30) % 360} 55% 45%))` }}>
      {initials}
    </span>
  );
}

export function Spinner({ className }: { className?: string }) {
  return <Loader2 className={cx("h-4 w-4 animate-spin text-ink-3", className)} />;
}

export function Tabs<T extends string>({ value, onChange, tabs }: { value: T; onChange: (v: T) => void; tabs: { value: T; label: ReactNode; count?: number }[] }) {
  return (
    <div className="flex gap-1 border-b border-line">
      {tabs.map((t) => (
        <button key={t.value} onClick={() => onChange(t.value)} className={cx("relative -mb-px px-3 py-2 text-[13px] font-medium transition", value === t.value ? "text-ink" : "text-ink-3 hover:text-ink-2")}>
          {t.label}{t.count !== undefined && <span className="ml-1.5 rounded-full bg-ink/[.07] px-1.5 text-[10.5px]">{t.count}</span>}
          {value === t.value && <span className="absolute inset-x-2 bottom-0 h-[2px] rounded-full bg-brand" />}
        </button>
      ))}
    </div>
  );
}

/* ---------------- Sheet (macOS modal that drops from the title bar) ---------------- */
export function Sheet({ open, onClose, title, children, footer, width = 520 }: { open: boolean; onClose: () => void; title: ReactNode; children: ReactNode; footer?: ReactNode; width?: number }) {
  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);
  useEffect(() => {
    if (!open) return;
    const k = (e: KeyboardEvent) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", k);
    return () => window.removeEventListener("keydown", k);
  }, [open, onClose]);
  if (!open || !mounted) return null;
  return createPortal(
    <div className="fixed inset-0 z-[80] flex items-start justify-center overflow-y-auto bg-black/25 px-4 pb-10 pt-[8vh] animate-fade" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
      <div role="dialog" aria-modal className="w-full animate-sheet overflow-hidden rounded-window bg-panel shadow-window" style={{ maxWidth: width }}>
        <header className="flex items-center justify-between border-b border-line/70 px-4 py-3">
          <h2 className="font-sans text-[14px] font-semibold">{title}</h2>
          <button onClick={onClose} className="grid h-6 w-6 place-items-center rounded-full text-ink-3 hover:bg-ink/[.06] hover:text-ink" aria-label="Close"><X className="h-4 w-4" /></button>
        </header>
        <div className="max-h-[70vh] overflow-y-auto p-4">{children}</div>
        {footer && <footer className="flex items-center justify-end gap-2 border-t border-line/70 bg-sunken/60 px-4 py-2.5">{footer}</footer>}
      </div>
    </div>,
    document.body,
  );
}

/* ---------------- Popover menu ---------------- */
export function Menu({ trigger, items, align = "right" }: { trigger: ReactNode; items: ({ label: ReactNode; onClick: () => void; danger?: boolean; icon?: ReactNode } | "sep")[]; align?: "left" | "right" }) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const h = (e: MouseEvent) => ref.current && !ref.current.contains(e.target as Node) && setOpen(false);
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, []);
  return (
    <div className="relative" ref={ref}>
      <div onClick={() => setOpen((o) => !o)}>{trigger}</div>
      {open && (
        <div className={cx("glass absolute z-50 mt-1 min-w-[180px] animate-pop rounded-[9px] p-1 shadow-pop", align === "right" ? "right-0" : "left-0")}>
          {items.map((it, i) => it === "sep" ? <div key={i} className="my-1 h-px bg-line" /> : (
            <button key={i} onClick={() => { setOpen(false); it.onClick(); }} className={cx("flex w-full items-center gap-2 rounded-[5px] px-2.5 py-1.5 text-left text-[13px] hover:bg-brand hover:text-white", it.danger && "text-bad")}>
              {it.icon}{it.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

/* ---------------- Toasts & confirm ---------------- */
type Toast = { id: number; kind: "ok" | "error" | "info"; text: string };
const ToastCtx = createContext<{ push: (kind: Toast["kind"], text: string) => void; confirm: (o: ConfirmOpts) => Promise<boolean> } | null>(null);
type ConfirmOpts = { title: string; body?: ReactNode; confirmLabel?: string; danger?: boolean };

export function UIProvider({ children }: { children: ReactNode }) {
  const [toasts, setToasts] = useState<Toast[]>([]);
  const [confirmState, setConfirm] = useState<(ConfirmOpts & { resolve: (v: boolean) => void }) | null>(null);
  const push = useCallback((kind: Toast["kind"], text: string) => {
    const id = Date.now() + Math.random();
    setToasts((t) => [...t, { id, kind, text }]);
    setTimeout(() => setToasts((t) => t.filter((x) => x.id !== id)), kind === "error" ? 6000 : 3200);
  }, []);
  const confirm = useCallback((o: ConfirmOpts) => new Promise<boolean>((resolve) => setConfirm({ ...o, resolve })), []);
  useEffect(() => {
    const h = (e: Event) => push("error", (e as CustomEvent<string>).detail);
    window.addEventListener("tp:error", h);
    return () => window.removeEventListener("tp:error", h);
  }, [push]);
  return (
    <ToastCtx.Provider value={{ push, confirm }}>
      {children}
      <div className="pointer-events-none fixed right-4 top-14 z-[90] flex w-[340px] flex-col gap-2">
        {toasts.map((t) => (
          <div key={t.id} className="glass pointer-events-auto flex animate-sheet items-start gap-2.5 rounded-[11px] px-3.5 py-3 shadow-pop">
            {t.kind === "ok" ? <CheckCircle2 className="mt-px h-4 w-4 shrink-0 text-ok" /> : t.kind === "error" ? <AlertTriangle className="mt-px h-4 w-4 shrink-0 text-bad" /> : <Info className="mt-px h-4 w-4 shrink-0 text-info" />}
            <p className="text-[12.5px] leading-snug">{t.text}</p>
          </div>
        ))}
      </div>
      <Sheet open={!!confirmState} onClose={() => { confirmState?.resolve(false); setConfirm(null); }} title={confirmState?.title ?? ""} width={420}
        footer={<>
          <Button onClick={() => { confirmState?.resolve(false); setConfirm(null); }}>Cancel</Button>
          <Button variant={confirmState?.danger ? "danger" : "primary"} onClick={() => { confirmState?.resolve(true); setConfirm(null); }}>{confirmState?.confirmLabel ?? "Confirm"}</Button>
        </>}>
        <div className="text-[13px] text-ink-2">{confirmState?.body}</div>
      </Sheet>
    </ToastCtx.Provider>
  );
}

export function useUI() {
  const c = useContext(ToastCtx);
  if (!c) throw new Error("useUI outside UIProvider");
  return c;
}

/* ---------------- API client ---------------- */
export class ClientApiError extends Error {
  constructor(public status: number, public code: string, message: string, public details?: any) {
    super(message);
  }
}

/** Calls the Platform REST API (/api/v1) with the session cookie; throws ClientApiError with the API's error body. */
export async function api<T = any>(path: string, init: { method?: string; body?: unknown; idempotent?: boolean } = {}): Promise<T> {
  const res = await fetch(path.startsWith("/api") ? path : `/api/v1${path}`, {
    method: init.method ?? (init.body !== undefined ? "POST" : "GET"),
    headers: { "Content-Type": "application/json", ...(init.idempotent ? { "Idempotency-Key": crypto.randomUUID() } : {}) },
    body: init.body !== undefined ? JSON.stringify(init.body) : undefined,
  });
  const text = await res.text();
  const json = text ? JSON.parse(text) : {};
  if (!res.ok) {
    const err = json?.error ?? {};
    throw new ClientApiError(res.status, err.code ?? "error", err.message ?? `Request failed (${res.status})`, err.details);
  }
  return json as T;
}

/** Wraps an async action with loading state + error toast. */
export function useAction() {
  const { push } = useUI();
  const [busy, setBusy] = useState(false);
  const run = useCallback(async <T,>(fn: () => Promise<T>, okText?: string): Promise<T | undefined> => {
    setBusy(true);
    try {
      const r = await fn();
      if (okText) push("ok", okText);
      return r;
    } catch (e) {
      push("error", e instanceof Error ? e.message : String(e));
      return undefined;
    } finally {
      setBusy(false);
    }
  }, [push]);
  return { busy, run };
}

export function PageHeader({ title, subtitle, actions, children }: { title: ReactNode; subtitle?: ReactNode; actions?: ReactNode; children?: ReactNode }) {
  return (
    <div className="mb-5 flex flex-wrap items-end justify-between gap-3">
      <div className="min-w-0">
        <h1 className="text-[22px] font-bold leading-tight">{title}</h1>
        {subtitle && <p className="mt-0.5 text-[13px] text-ink-3">{subtitle}</p>}
        {children}
      </div>
      {actions && <div className="flex flex-wrap items-center gap-2">{actions}</div>}
    </div>
  );
}
