/* ui.jsx — shared primitives. Exported to window for cross-file use. */
const { useState, useRef, useEffect, useCallback } = React;

/* ---------- icons (simple stroke set) ---------- */
const IPATHS = {
  back: "M15 5l-7 7 7 7", fwd: "M9 5l7 7-7 7",
  globe: "M12 3a9 9 0 100 18 9 9 0 000-18zM3 12h18M12 3c2.5 2.5 2.5 15.5 0 18M12 3c-2.5 2.5-2.5 15.5 0 18",
  plus: "M12 5v14M5 12h14", minus: "M5 12h14",
  camera: "M4 8a2 2 0 012-2h1.5l1-1.6a1 1 0 01.85-.4h5.3a1 1 0 01.85.4L16.5 6H18a2 2 0 012 2v9a2 2 0 01-2 2H6a2 2 0 01-2-2V8z M12 16.5a3 3 0 100-6 3 3 0 000 6z",
  check: "M5 13l4 4L19 7", x: "M6 6l12 12M18 6L6 18",
  home: "M4 11l8-7 8 7M6 10v9h12v-9", settings: "M12 9a3 3 0 100 6 3 3 0 000-6z M19 12a7 7 0 00-.12-1.3l2-1.55-2-3.46-2.36.95a7 7 0 00-2.26-1.3L13.9 2h-3.8l-.36 2.34a7 7 0 00-2.26 1.3L5.12 4.7l-2 3.46 2 1.55A7 7 0 005 12c0 .44.04.87.12 1.3l-2 1.55 2 3.46 2.36-.95a7 7 0 002.26 1.3L10.1 22h3.8l.36-2.34a7 7 0 002.26-1.3l2.36.95 2-3.46-2-1.55c.08-.43.12-.86.12-1.3z",
  basket: "M5 9h14l-1.2 9.2a2 2 0 01-2 1.8H8.2a2 2 0 01-2-1.8L5 9z M8.5 9l2-5M15.5 9l-2-5M3.5 9h17",
  receipt: "M6 3h12v18l-2.5-1.5L13 21l-2.5-1.5L8 21l-2-1.5V3z M9 8h6M9 12h6M9 16h3",
  edit: "M4 20h4l10-10-4-4L4 16v4z M13.5 6.5l4 4", trash: "M5 7h14M9 7V5a1 1 0 011-1h4a1 1 0 011 1v2M7 7l1 13h8l1-13",
  user: "M12 12a4 4 0 100-8 4 4 0 000 8z M4 21a8 8 0 0116 0",
  mail: "M3 6h18v12H3z M3 7l9 6 9-6", building: "M5 21V4a1 1 0 011-1h8a1 1 0 011 1v17 M15 9h3a1 1 0 011 1v11 M8 7h2M8 11h2M8 15h2",
  logout: "M14 8V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2h6a2 2 0 002-2v-2M9 12h11m0 0l-3-3m3 3l-3 3",
  shield: "M12 3l8 3v5c0 5-3.5 8.5-8 10-4.5-1.5-8-5-8-10V6l8-3z M9 12l2 2 4-4",
  scale: "M12 4v16M5 8h14M5 8l-2.5 6h5L5 8z M19 8l-2.5 6h5L19 8z M8 20h8",
  warn: "M12 4l9 16H3l9-16z M12 10v4M12 17h.01",
  send: "M4 12l16-8-6 16-3-6-7-2z", clock: "M12 21a9 9 0 100-18 9 9 0 000 18z M12 8v4l3 2",
  doc: "M6 3h8l4 4v14H6V3z M14 3v4h4 M9 13h6M9 17h6", chevDown: "M6 9l6 6 6-6",
  list: "M8 6h12M8 12h12M8 18h12M4 6h.01M4 12h.01M4 18h.01",
  search: "M11 18a7 7 0 100-14 7 7 0 000 14z M21 21l-4-4",
  lock: "M7 11V8a5 5 0 0110 0v3 M5 11h14v10H5z M12 15v3",
};
function Icon({ name, size = 22, stroke = 2, style }) {
  const d = IPATHS[name] || "";
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
      stroke="currentColor" strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round" style={style}>
      {d.split("M").filter(Boolean).map((seg, i) => <path key={i} d={"M" + seg} />)}
    </svg>
  );
}

/* ---------- buttons ---------- */
function Button({ variant = "primary", icon, children, className = "", ...p }) {
  return (
    <button className={`btn btn-${variant} ${className}`} {...p}>
      {icon && <Icon name={icon} size={19} />}
      {children}
    </button>
  );
}

/* ---------- field wrapper ---------- */
function Field({ label, required, hint, children }) {
  return (
    <div className="field">
      {label && <label className="label">{label}{required && <span className="req">•</span>}</label>}
      {children}
      {hint && <div className="hint">{hint}</div>}
    </div>
  );
}

/* ---------- select ---------- */
function Select({ value, onChange, children, ...p }) {
  return (
    <div className="select-wrap">
      <select className="select" value={value} onChange={(e) => onChange(e.target.value)} {...p}>
        {children}
      </select>
    </div>
  );
}

/* ---------- status badge ---------- */
function StatusBadge({ status, lang }) {
  return <span className={`badge is-${status}`}><i className="dot"></i>{window.t(lang, status)}</span>;
}

/* ---------- step progress ---------- */
function Steps({ total, current }) {
  return (
    <div className="steps">
      {Array.from({ length: total }).map((_, i) =>
        <div key={i} className={`seg ${i <= current ? "done" : ""}`}></div>)}
    </div>
  );
}

/* ---------- bottom sheet ---------- */
function Sheet({ onClose, children }) {
  return (
    <div className="sheet-bg" onClick={onClose}>
      <div className="sheet" onClick={(e) => e.stopPropagation()}>
        <div className="grip"></div>
        {children}
      </div>
    </div>
  );
}

/* ---------- photo capture w/ real compression ---------- */
function PhotoCapture({ label, hint, value, onChange, lang }) {
  const inputRef = useRef(null);
  const [busy, setBusy] = useState(false);
  async function handle(e) {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    setBusy(true);
    const out = await window.compressImage(file, 1024, 0.6);
    setBusy(false);
    if (out) onChange(out);
    e.target.value = "";
  }
  return (
    <div className="field">
      {label && <label className="label">{label}</label>}
      <div className={`photo-slot ${value ? "filled" : ""}`} onClick={() => !value && inputRef.current.click()}>
        {busy ? <div className="spin"></div> : value ? (
          <React.Fragment>
            <img src={value.dataUrl} alt="" />
            <div className="meta">{value.w}×{value.h} · {value.kb} KB</div>
            <button className="x" onClick={(e) => { e.stopPropagation(); onChange(null); }}><Icon name="x" size={16} /></button>
          </React.Fragment>
        ) : (
          <div className="center stack gap-sm" style={{ alignItems: "center" }}>
            <Icon name="camera" size={28} />
            <div style={{ fontSize: 13, fontWeight: 600 }}>{window.t(lang, "takePhoto")}</div>
            {hint && <div className="hint" style={{ maxWidth: 180 }}>{hint}</div>}
          </div>
        )}
      </div>
      <input ref={inputRef} type="file" accept="image/*" capture="environment" hidden onChange={handle} />
    </div>
  );
}

/* ---------- draw-to-sign pad (for seller) ---------- */
function SignPad({ value, onChange }) {
  const ref = useRef(null);
  const drawing = useRef(false);
  const dirty = useRef(false);

  useEffect(() => {
    const cv = ref.current;
    const dpr = window.devicePixelRatio || 1;
    const rect = cv.getBoundingClientRect();
    cv.width = rect.width * dpr; cv.height = rect.height * dpr;
    const ctx = cv.getContext("2d");
    ctx.scale(dpr, dpr);
    ctx.lineWidth = 2.4; ctx.lineCap = "round"; ctx.lineJoin = "round"; ctx.strokeStyle = "#15151a";
    if (value) { const img = new Image(); img.onload = () => ctx.drawImage(img, 0, 0, rect.width, rect.height); img.src = value; }
  }, []);

  function pos(e) {
    const r = ref.current.getBoundingClientRect();
    const p = e.touches ? e.touches[0] : e;
    return { x: p.clientX - r.left, y: p.clientY - r.top };
  }
  function start(e) { e.preventDefault(); drawing.current = true; const ctx = ref.current.getContext("2d"); const { x, y } = pos(e); ctx.beginPath(); ctx.moveTo(x, y); }
  function move(e) { if (!drawing.current) return; e.preventDefault(); const ctx = ref.current.getContext("2d"); const { x, y } = pos(e); ctx.lineTo(x, y); ctx.stroke(); dirty.current = true; }
  function end() { if (!drawing.current) return; drawing.current = false; if (dirty.current) onChange(ref.current.toDataURL("image/png")); }
  function clear() { const cv = ref.current; cv.getContext("2d").clearRect(0, 0, cv.width, cv.height); dirty.current = false; onChange(null); }

  return (
    <div className="stack gap-sm">
      <canvas ref={ref} className="sig-pad"
        onMouseDown={start} onMouseMove={move} onMouseUp={end} onMouseLeave={end}
        onTouchStart={start} onTouchMove={move} onTouchEnd={end} />
      <button className="btn btn-quiet btn-sm" style={{ width: "auto", alignSelf: "flex-end" }} onClick={clear}>
        <Icon name="x" size={15} /> clear
      </button>
    </div>
  );
}

/* ---------- tap-to-sign (stored signature for creator/approver) ---------- */
function StoredSign({ name, signature, signed, onToggle, lang }) {
  return (
    <button className={`sig-stored ${signed ? "signed" : ""}`} onClick={onToggle} style={{ width: "100%", border: signed ? undefined : "1px dashed var(--line)", cursor: "pointer" }}>
      {signed ? signature : <span style={{ fontFamily: "var(--font)", fontSize: 14, color: "var(--muted)", fontWeight: 600 }}>
        <Icon name="edit" size={16} style={{ verticalAlign: "-3px", marginRight: 6 }} />{window.t(lang, "tapToSign")}</span>}
    </button>
  );
}

Object.assign(window, { Icon, Button, Field, Select, StatusBadge, Steps, Sheet, PhotoCapture, SignPad, StoredSign,
  useState, useRef, useEffect, useCallback });
