/* ============================================================
   Shared UI — icons, helpers, chart. Exported to window.
   ============================================================ */
const { useState, useEffect, useRef, useMemo } = React;
const D = window.PavData;

/* ---------- Icon set ---------- */
const ICONS = {
  grid: "M4 4h7v7H4zM13 4h7v7h-7zM4 13h7v7H4zM13 13h7v7h-7z",
  users: "M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8ZM22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75",
  calc: "M5 3h14a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1ZM8 7h8M8 11h2M14 11h2M8 15h2M14 15h2M8 18h2",
  doc: "M7 3h7l4 4v14H7a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1ZM14 3v4h4M9 13h6M9 17h4",
  report: "M4 19V5M4 19h16M8 15l3-4 3 2 4-6",
  building: "M4 21V8l7-4 7 4v13M9 21v-5h4v5M9 11h.01M13 11h.01",
  gear: "M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM19.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-2.7 1.27V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 7 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 2.6 14a2 2 0 0 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06A2 2 0 1 1 6.64 4.3l.06.06a1.65 1.65 0 0 0 1.82.33H8.6a1.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.82V10a1.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",
  search: "M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16ZM21 21l-4.3-4.3",
  bell: "M18 8a6 6 0 1 0-12 0c0 7-3 9-3 9h18s-3-2-3-9M13.7 21a2 2 0 0 1-3.4 0",
  chevDown: "M6 9l6 6 6-6",
  chevUp: "M18 15l-6-6-6 6",
  chevRight: "M9 6l6 6-6 6",
  chevLeft: "M15 6l-6 6 6 6",
  check: "M5 12.5 10 17l9-10",
  x: "M6 6l12 12M18 6 6 18",
  plus: "M12 5v14M5 12h14",
  logout: "M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9",
  download: "M12 3v12M7 11l5 4 5-4M5 21h14",
  send: "M22 2 11 13M22 2l-7 20-4-9-9-4 20-7Z",
  calendar: "M3 9h18M8 3v4M16 3v4M5 5h14a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Z",
  shield: "M12 3 5 6v5c0 4.4 3 8 7 10 4-2 7-5.6 7-10V6l-7-3ZM9 12l2 2 4-4.5",
  wallet: "M19 7H5a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-8a2 2 0 0 0-2-2ZM3 9V7a2 2 0 0 1 2-2h11M17 13h.01",
  trend: "M3 17l6-6 4 4 8-8M21 7v6M21 7h-6",
  clock: "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18ZM12 7v5l3 2",
  briefcase: "M20 7H4a1 1 0 0 0-1 1v11a1 1 0 0 0 1 1h16a1 1 0 0 0 1-1V8a1 1 0 0 0-1-1ZM8 7V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M3 12h18",
  mail: "M4 5h16a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1ZM3 7l9 6 9-6",
  print: "M6 9V3h12v6M6 18H4a1 1 0 0 1-1-1v-5a1 1 0 0 1 1-1h16a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1h-2M6 14h12v7H6z",
  filter: "M3 5h18l-7 8v5l-4 2v-7L3 5Z",
  sun: "M12 17a5 5 0 1 0 0-10 5 5 0 0 0 0 10ZM12 1v2M12 21v2M4.2 4.2l1.4 1.4M18.4 18.4l1.4 1.4M1 12h2M21 12h2M4.2 19.8l1.4-1.4M18.4 5.6l1.4-1.4",
  moon: "M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8Z",
  refresh: "M21 12a9 9 0 1 1-3-6.7L21 8M21 3v5h-5",
  bolt: "M13 2 3 14h7l-1 8 10-12h-7l1-8Z",
};
function Icon({ name, size = 19, sw = 1.8, fill = "none", style }) {
  const d = ICONS[name] || "";
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={fill}
      stroke={fill === "none" ? "currentColor" : "none"} strokeWidth={sw}
      strokeLinecap="round" strokeLinejoin="round" style={style} aria-hidden="true">
      {d.split("M").filter(Boolean).map((seg, i) => <path key={i} d={"M" + seg} />)}
    </svg>
  );
}

/* ---------- Small components ---------- */
function Badge({ kind, children }) { return <span className={"badge-st " + kind}>{children}</span>; }

function statusBadge(status) {
  if (status === "aktyvus") return <Badge kind="ok">Aktyvus</Badge>;
  if (status === "atostogos") return <Badge kind="info">Atostogos</Badge>;
  if (status === "liga") return <Badge kind="warn">Liga</Badge>;
  return <Badge kind="muted">{status}</Badge>;
}

function Avatar({ text, size = 32, className = "av" }) {
  return <span className={className} style={{ width: size, height: size, fontSize: size * 0.38 }}>{text}</span>;
}

/* ---------- Bar chart (SVG) ---------- */
function BarChart({ data, accentLast = true }) {
  const W = 560, H = 220, pad = { t: 24, r: 8, b: 28, l: 8 };
  const max = Math.max(...data.map((d) => d.gross)) * 1.12;
  const bw = (W - pad.l - pad.r) / data.length;
  const barW = bw * 0.46;
  const y = (v) => pad.t + (H - pad.t - pad.b) * (1 - v / max);
  const gridVals = [0, max * 0.5, max];
  return (
    <svg className="chart" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none">
      {gridVals.map((g, i) => (
        <line key={i} className="grid-line" x1={pad.l} x2={W - pad.r} y1={y(g)} y2={y(g)} />
      ))}
      {data.map((d, i) => {
        const x = pad.l + bw * i + (bw - barW) / 2;
        const h = H - pad.b - y(d.gross);
        const muted = accentLast && i < data.length - 1;
        return (
          <g key={i}>
            <rect className={"bar" + (muted ? " muted" : "")} x={x} y={y(d.gross)} width={barW} height={Math.max(2, h)} rx="5" />
            <text className="val-lbl" x={x + barW / 2} y={y(d.gross) - 7} textAnchor="middle">{Math.round(d.gross / 1000) + "k"}</text>
            <text className="axis-lbl" x={x + barW / 2} y={H - 9} textAnchor="middle">{d.month}</text>
          </g>
        );
      })}
    </svg>
  );
}

/* ---------- Toast hook ---------- */
function useToast() {
  const [msg, setMsg] = useState(null);
  const show = (m) => { setMsg(m); };
  useEffect(() => {
    if (!msg) return;
    const t = setTimeout(() => setMsg(null), 2600);
    return () => clearTimeout(t);
  }, [msg]);
  const node = (
    <div className={"toast" + (msg ? " in" : "")}>
      <Icon name="check" size={16} sw={2.4} /> {msg}
    </div>
  );
  return [show, node];
}

/* ---------- Modal ---------- */
function Modal({ title, onClose, children, footer, wide }) {
  const [vis, setVis] = useState(false);
  useEffect(() => { const t = setTimeout(() => setVis(true), 10); return () => clearTimeout(t); }, []);
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") close(); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  });
  const close = () => { setVis(false); setTimeout(onClose, 200); };
  return (
    <div className={"modal-scrim" + (vis ? " in" : "")} onMouseDown={(e) => { if (e.target === e.currentTarget) close(); }}>
      <div className={"modal" + (vis ? " in" : "") + (wide ? " wide" : "")} role="dialog" aria-modal="true">
        <div className="modal-head">
          <h3>{title}</h3>
          <button className="x" onClick={close} aria-label="Uždaryti"><Icon name="x" size={16} /></button>
        </div>
        <div className="modal-body">{children}</div>
        {footer && <div className="modal-foot">{footer}</div>}
      </div>
    </div>
  );
}

/* ---------- Form fields ---------- */
function Field({ label, value, onChange, type = "text", placeholder, span, inputMode, suffix }) {
  return (
    <label className="ff" style={span ? { gridColumn: "1 / -1" } : null}>
      <span className="ff-label">{label}</span>
      <span className="ff-input-wrap">
        <input className="ff-input" type={type} value={value} placeholder={placeholder} inputMode={inputMode}
          onChange={(e) => onChange(e.target.value)} />
        {suffix && <span className="ff-suffix">{suffix}</span>}
      </span>
    </label>
  );
}
function SelectField({ label, value, onChange, options, span }) {
  return (
    <label className="ff" style={span ? { gridColumn: "1 / -1" } : null}>
      <span className="ff-label">{label}</span>
      <select className="fld-select" style={{ width: "100%", height: 42 }} value={value} onChange={(e) => onChange(e.target.value)}>
        {options.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
      </select>
    </label>
  );
}
function ToggleField({ label, hint, value, onChange }) {
  return (
    <div className="ff-toggle" onClick={() => onChange(!value)}>
      <div>
        <div className="ff-label" style={{ marginBottom: 2 }}>{label}</div>
        {hint && <div style={{ fontSize: 12, color: "var(--ink-faint)" }}>{hint}</div>}
      </div>
      <span className={"switch" + (value ? " on" : "")}><span className="knob"></span></span>
    </div>
  );
}

Object.assign(window, { Icon, Badge, statusBadge, Avatar, BarChart, useToast, Modal, Field, SelectField, ToggleField });

/* ---------- File download helper ---------- */
function downloadFile(filename, content, mime) {
  try {
    const blob = new Blob([content], { type: mime || "text/plain;charset=utf-8" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url; a.download = filename;
    document.body.appendChild(a); a.click(); a.remove();
    setTimeout(() => URL.revokeObjectURL(url), 1000);
  } catch (e) {}
}
window.downloadFile = downloadFile;
