/* Tachiara — shared UI primitives.
 * All Lucide icons inlined as React SVGs (no external lucide-react dep).
 * Style with className="icon" / "icon-sm" / "icon-lg" via parent.
 */

const Icon = ({ d, paths, children, ...rest }) => (
  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"
       fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
       {...rest}>
    {children}
  </svg>
);

const I = {
  home:        () => <Icon><path d="m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></Icon>,
  wallet:      () => <Icon><path d="M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"/><path d="M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"/></Icon>,
  users:       () => <Icon><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></Icon>,
  user:        () => <Icon><path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></Icon>,
  chart:       () => <Icon><path d="M3 3v18h18"/><path d="M7 16V8"/><path d="M12 16v-5"/><path d="M17 16v-3"/></Icon>,
  plus:        () => <Icon><path d="M12 5v14M5 12h14"/></Icon>,
  arrowRight:  () => <Icon><path d="M5 12h14M13 5l7 7-7 7"/></Icon>,
  arrowLeft:   () => <Icon><path d="M19 12H5M12 19l-7-7 7-7"/></Icon>,
  check:       () => <Icon><polyline points="20 6 9 17 4 12"/></Icon>,
  x:           () => <Icon><path d="M18 6 6 18M6 6l12 12"/></Icon>,
  copy:        () => <Icon><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></Icon>,
  bell:        () => <Icon><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/></Icon>,
  trash:       () => <Icon><path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></Icon>,
  edit:        () => <Icon><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="m18.5 2.5 3 3L12 15l-4 1 1-4z"/></Icon>,
  settings:    () => <Icon><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 0 1 0 2.83 2 2 0 0 1-2.83 0l-.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-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-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-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 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 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1"/></Icon>,
  receipt:     () => <Icon><path d="M4 2v20l2-2 2 2 2-2 2 2 2-2 2 2 2-2 2 2V2l-2 2-2-2-2 2-2-2-2 2-2-2-2 2-2-2z"/><path d="M8 7h8M8 11h8M8 15h6"/></Icon>,
  share:       () => <Icon><path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"/><polyline points="16 6 12 2 8 6"/><line x1="12" y1="2" x2="12" y2="15"/></Icon>,
  link:        () => <Icon><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></Icon>,
  doorOpen:    () => <Icon><path d="M13 4h3a2 2 0 0 1 2 2v14"/><path d="M2 20h3"/><path d="M13 20h9"/><path d="M10 12v.01"/><path d="M13 4.562V20l-7-2V6.5L13 4.562z"/></Icon>,
  qr:          () => <Icon><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><path d="M14 14h3v3h-3zM21 14v3M14 21h3M17 17h4M21 21v-1"/></Icon>,
  logout:      () => <Icon><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></Icon>,
  calendar:    () => <Icon><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></Icon>,
  search:      () => <Icon><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></Icon>,
  more:        () => <Icon><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/></Icon>,
  bank:        () => <Icon><path d="m3 21 18 0"/><path d="M5 21V10l7-5 7 5v11"/><path d="M9 21V14h6v7"/></Icon>,
  arrowDownRight: () => <Icon><line x1="7" y1="7" x2="17" y2="17"/><polyline points="17 7 17 17 7 17"/></Icon>,
  arrowUpRight: () => <Icon><line x1="7" y1="17" x2="17" y2="7"/><polyline points="7 7 17 7 17 17"/></Icon>,
  handshake:   () => <Icon><path d="m11 17 2 2a1 1 0 1 0 3-3"/><path d="m14 14 2.5 2.5a1 1 0 1 0 3-3l-3.88-3.88a3 3 0 0 0-4.24 0l-.88.88a1 1 0 1 1-3-3l2.81-2.81a5.79 5.79 0 0 1 7.06-.87l.47.28a2 2 0 0 0 1.42.25L21 4"/><path d="m21 3 1 11h-2"/><path d="M3 3 2 14l6.5 6.5a1 1 0 1 0 3-3"/><path d="M3 4h8"/></Icon>,
  filePlus:    () => <Icon><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="12" y1="18" x2="12" y2="12"/><line x1="9" y1="15" x2="15" y2="15"/></Icon>,
  inbox:       () => <Icon><polyline points="22 12 16 12 14 15 10 15 8 12 2 12"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/></Icon>,
};

// ── Avatar ────────────────────────────────────────────────────────────
function Avatar({ user, size = "md" }) {
  if (!user) return null;
  const cls = "avatar" + (size === "sm" ? " avatar-sm" : size === "lg" ? " avatar-lg" : size === "xl" ? " avatar-xl" : "");
  return (
    <div className={cls} style={{ background: window.QC.avatarColor(user.name) }}>
      {window.QC.initials(user.name)}
    </div>
  );
}

function AvatarStack({ users, max = 4 }) {
  const shown = users.slice(0, max);
  const extra = users.length - shown.length;
  return (
    <div className="avatar-stack">
      {shown.map(u => <Avatar key={u.id} user={u} size="sm" />)}
      {extra > 0 && (
        <div className="avatar avatar-sm" style={{ background: "var(--wf-slate-700)" }}>
          +{extra}
        </div>
      )}
    </div>
  );
}

// ── Button ────────────────────────────────────────────────────────────
function Button({ variant = "primary", size, icon, children, ...rest }) {
  const cls = "btn btn-" + variant + (size === "sm" ? " btn-sm" : size === "lg" ? " btn-lg" : "");
  return (
    <button className={cls} {...rest}>
      {icon ? <span className="icon">{icon}</span> : null}
      {children}
    </button>
  );
}

// ── Modal ─────────────────────────────────────────────────────────────
function Modal({ open, onClose, title, children, footer, size }) {
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose && onClose(); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className={"modal" + (size === "lg" ? " modal-lg" : "")} onClick={e => e.stopPropagation()}>
        <div className="modal-header">
          <div className="modal-title">{title}</div>
          <button className="btn btn-ghost btn-icon" onClick={onClose} aria-label="Đóng">
            <span className="icon"><I.x /></span>
          </button>
        </div>
        <div className="modal-body">{children}</div>
        {footer && <div className="modal-footer">{footer}</div>}
      </div>
    </div>
  );
}

// ── Toast (host pinned at root) ───────────────────────────────────────
const ToastContext = React.createContext({ toast: () => {} });

function ToastHost({ children }) {
  const [items, setItems] = React.useState([]);
  const toast = React.useCallback((msg) => {
    const id = Math.random().toString(36).slice(2);
    setItems(prev => [...prev, { id, msg }]);
    setTimeout(() => setItems(prev => prev.filter(i => i.id !== id)), 2600);
  }, []);
  return (
    <ToastContext.Provider value={{ toast }}>
      {children}
      <div className="toast-host">
        {items.map(i => <div key={i.id} className="toast">{i.msg}</div>)}
      </div>
    </ToastContext.Provider>
  );
}
const useToast = () => React.useContext(ToastContext).toast;

// ── Number input that handles VND nicely ──────────────────────────────
function MoneyInput({ value, onChange, placeholder = "0", ...rest }) {
  const display = value ? Number(value).toLocaleString("vi-VN") : "";
  return (
    <div className="input-prefix">
      <input
        className="input"
        type="text"
        inputMode="numeric"
        value={display}
        placeholder={placeholder}
        onChange={(e) => {
          const raw = e.target.value.replace(/[^0-9]/g, "");
          onChange(raw ? Number(raw) : 0);
        }}
        {...rest}
      />
      <div className="prefix" style={{ borderLeft: "1px solid var(--wf-border)", borderRight: 0 }}>₫</div>
    </div>
  );
}

// ── Mini bar/donut charts ─────────────────────────────────────────────
function Donut({ segments, size = 160, thickness = 18 }) {
  const total = segments.reduce((s, x) => s + x.value, 0) || 1;
  const radius = (size - thickness) / 2;
  const circ = 2 * Math.PI * radius;
  let offset = 0;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      <circle cx={size / 2} cy={size / 2} r={radius}
              fill="none" stroke="var(--wf-bg-muted)" strokeWidth={thickness} />
      {segments.map((seg, i) => {
        const len = (seg.value / total) * circ;
        const el = (
          <circle key={i}
            cx={size / 2} cy={size / 2} r={radius}
            fill="none" stroke={seg.color} strokeWidth={thickness}
            strokeDasharray={`${len} ${circ - len}`}
            strokeDashoffset={-offset}
            transform={`rotate(-90 ${size / 2} ${size / 2})`}
            strokeLinecap="butt"
          />
        );
        offset += len;
        return el;
      })}
    </svg>
  );
}

function BarList({ items, max }) {
  const m = max || Math.max(...items.map(i => i.value), 1);
  return (
    <div>
      {items.map((it, i) => (
        <div key={i} className="bar-row">
          <div className="text-fg-2" style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
            {it.label}
          </div>
          <div className="bar-track">
            <div className="bar-fill" style={{ width: ((it.value / m) * 100) + "%", background: it.color || "var(--wf-slate-900)" }} />
          </div>
          <div className="mono text-fg-2" style={{ textAlign: "right" }}>
            {window.QC.formatVND(it.value)}
          </div>
        </div>
      ))}
    </div>
  );
}

// ── Tabs ──────────────────────────────────────────────────────────────
function Tabs({ tabs, value, onChange }) {
  return (
    <div className="tabs">
      {tabs.map(t => (
        <button key={t.value}
          className={"tab" + (t.value === value ? " active" : "")}
          onClick={() => onChange(t.value)}>
          {t.label}
          {t.count != null && <span className="badge" style={{ marginLeft: 6 }}>{t.count}</span>}
        </button>
      ))}
    </div>
  );
}

// ── Field ─────────────────────────────────────────────────────────────
function Field({ label, hint, error, children }) {
  return (
    <div className="field">
      {label && <label className="field-label">{label}</label>}
      {children}
      {error ? <div className="field-error">{error}</div> : hint ? <div className="field-hint">{hint}</div> : null}
    </div>
  );
}

// ── Empty state ───────────────────────────────────────────────────────
function Empty({ icon, title, children, action }) {
  return (
    <div className="empty">
      {icon ? <div className="empty-icon icon-lg" style={{ width: 48, height: 48 }}>{icon}</div> : null}
      {title && <div className="empty-title">{title}</div>}
      {children && <div className="text-sm">{children}</div>}
      {action && <div style={{ marginTop: 16 }}>{action}</div>}
    </div>
  );
}

// ── Copyable invite code ──────────────────────────────────────────────
function CopyCode({ code }) {
  const toast = useToast();
  const copy = () => {
    navigator.clipboard?.writeText(code);
    toast("Đã copy mã mời");
  };
  return (
    <button className="row-h" onClick={copy} style={{ gap: 6, cursor: "pointer" }} title="Copy">
      <span className="invite-code">{code}</span>
      <span className="icon icon-sm text-muted"><I.copy /></span>
    </button>
  );
}

Object.assign(window, {
  Icon, I, Avatar, AvatarStack,
  Button, Modal, ToastHost, ToastContext, useToast,
  MoneyInput, Donut, BarList, Tabs, Field, Empty, CopyCode,
});
