/* =====================================================
   Betting Tracker — shared brand primitives (React)
   Renders the Doinp "Soft Dark" markup: .glass panels,
   tactile pills, inset wells, hairline tables.
   Exports to window for the other babel scripts.
   ===================================================== */
const { useState, useEffect, useRef, useCallback, createContext, useContext } = React;

/* ---- context: state, dispatch, lang, t ---- */
const TrackerCtx = createContext(null);
const useTracker = () => useContext(TrackerCtx);

/* ---- Portal: render overlays at <body> so position:fixed is always
   viewport-relative (never trapped by an ancestor's stacking/containing block) ---- */
function Portal({ children }) {
  return ReactDOM.createPortal(children, document.body);
}

/* ---- icons: 24-box, 1.8 stroke, round, currentColor ---- */
const ICONS = {
  dashboard: "M4 13h7V4H4v9Zm9 7h7V4h-7v16ZM4 20h7v-5H4v5Z",
  bets: "M4 6h16M4 12h16M4 18h10",
  bankroll: "M3 7h18v10H3zM3 11h18M7 15h2",
  analytics: "M4 19V5m0 14h16M8 15l3-4 3 3 4-6",
  plus: "M12 5v14M5 12h14",
  close: "M6 6l12 12M18 6L6 18",
  save: "M5 4h11l3 3v13H5zM8 4v5h7V4M8 20v-6h8v6",
  download: "M12 4v11m0 0l-4-4m4 4l4-4M5 20h14",
  upload: "M12 20V9m0 0l-4 4m4-4l4 4M5 4h14",
  file: "M6 3h8l4 4v14H6zM14 3v4h4",
  filter: "M4 5h16l-6 8v5l-4 2v-7z",
  search: "M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14ZM20 20l-4-4",
  edit: "M4 20h4l10-10-4-4L4 16v4ZM14 6l4 4",
  trash: "M5 7h14M9 7V4h6v3M6 7l1 13h10l1-13",
  shield: "M12 3l8 3v6c0 5-3.5 8-8 10-4.5-2-8-5-8-10V6z",
  lock: "M6 11h12v9H6zM8 11V8a4 4 0 0 1 8 0v3",
  wifi: "M2 8.5a15 15 0 0 1 20 0M5 12a10 10 0 0 1 14 0M8.5 15.5a5 5 0 0 1 7 0M12 19h.01",
  arrowRight: "M5 12h14M13 6l6 6-6 6",
  check: "M5 12l5 5L20 6",
  chevron: "M9 6l6 6-6 6",
  wallet: "M3 7h15a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H4a1 1 0 0 1-1-1V7Zm0 0l0-1a1 1 0 0 1 1-1h11M17 13h.01",
  chart: "M4 20V4M4 20h16M9 16l3-5 3 2 4-7",
  target: "M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm0 4a5 5 0 1 0 0 10 5 5 0 0 0 0-10Zm0 4a1 1 0 1 0 0 2 1 1 0 0 0 0-2Z",
  layers: "M12 3l9 5-9 5-9-5 9-5ZM3 13l9 5 9-5",
  sliders: "M4 8h9M17 8h3M4 16h3M11 16h9M15 5v6M9 13v6",
  copy: "M9 9h10a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H9a1 1 0 0 1-1-1V10a1 1 0 0 1 1-1ZM5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1",
  history: "M3 12a9 9 0 1 0 3-6.7L3 8M3 4v4h4M12 8v4l3 2",
  gear: "M12 9.2a2.8 2.8 0 1 0 0 5.6 2.8 2.8 0 0 0 0-5.6ZM10.7 3h2.6l.35 2.3 1.6.93 2.16-.9 1.84 1.84-1.2 1.98.6 1.72 2.35.43v2.6l-2.35.43-.6 1.72 1.2 1.98-1.84 1.84-2.16-.9-1.6.93-.35 2.3h-2.6l-.35-2.3-1.6-.93-2.16.9-1.84-1.84 1.2-1.98-.6-1.72L2 13.3v-2.6l2.35-.43.6-1.72-1.2-1.98 1.84-1.84 2.16.9 1.6-.93z"
};
function Icon({ name, size = 18, style }) {
  const d = ICONS[name] || "";
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} fill="none"
      stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"
      style={style} aria-hidden="true">
      {d.split("M").filter(Boolean).map((seg, i) => <path key={i} d={"M" + seg} />)}
    </svg>
  );
}

/* ---- Panel (.glass) ---- */
function Panel({ children, className = "", style, pad = 24, hover = false }) {
  return (
    <div className={"glass trk-panel" + (hover ? " trk-panel--hover" : "") + (className ? " " + className : "")}
      style={{ padding: pad, ...style }}>
      {children}
    </div>
  );
}

/* ---- KPI stat ---- */
function Stat({ label, value, tone, sub, big }) {
  const cls = tone === "pos" ? "is-pos" : tone === "neg" ? "is-neg" : "";
  return (
    <div className="trk-stat">
      <div className="trk-stat__cap">{label}</div>
      <div className={"trk-stat__val " + cls + (big ? " trk-stat__val--big" : "")}>{value}</div>
      {sub != null && <div className="trk-stat__sub">{sub}</div>}
    </div>
  );
}

/* ---- eyebrow / section head ---- */
function SectionHead({ title, sub, right }) {
  return (
    <div className="trk-sechead">
      <div>
        <h2>{title}</h2>
        {sub && <p>{sub}</p>}
      </div>
      {right && <div className="trk-sechead__right">{right}</div>}
    </div>
  );
}

/* ---- Tag chip ---- */
function Tag({ children, tone }) {
  return <span className={"trk-tag" + (tone ? " trk-tag--" + tone : "")}>{children}</span>;
}

/* ---- Result badge ---- */
function ResultBadge({ result, t }) {
  const tone = (result === "won" || result === "half-won") ? "pos"
    : (result === "lost" || result === "half-lost") ? "neg"
      : result === "pending" ? "wait"
        : result === "cashout" ? "cash" : "mute";
  return <span className={"trk-res trk-res--" + tone}>{t ? t("res." + result) : result}</span>;
}

/* ---- Segmented control ---- */
function Segmented({ options, value, onChange, size }) {
  return (
    <div className={"segmented trk-seg" + (size === "sm" ? " trk-seg--sm" : "")} role="group">
      {options.map((o) => (
        <button key={o.value} type="button" aria-pressed={String(o.value === value)}
          onClick={() => onChange(o.value)}>{o.label}</button>
      ))}
    </div>
  );
}

/* ---- Toggle ---- */
function Toggle({ checked, onChange, label }) {
  return (
    <label className={"switch trk-switch" + (checked ? " is-on" : "")}>
      <input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)} />
      <span className="switch__track"><span className="switch__knob"></span></span>
      {label && <span className="trk-switch__label">{label}</span>}
    </label>
  );
}

/* ---- Buttons ---- */
function Btn({ children, variant = "ghost", icon, onClick, type = "button", disabled, className = "", size }) {
  return (
    <button type={type} disabled={disabled} onClick={onClick}
      className={"btn btn--" + variant + (size === "sm" ? " trk-btn--sm" : "") + (className ? " " + className : "")}>
      {icon && <Icon name={icon} size={size === "sm" ? 15 : 17} />}
      {children}
    </button>
  );
}

/* ---- Form fields ---- */
function Field({ label, hint, children, span }) {
  return (
    <label className="trk-field" style={span ? { gridColumn: "1 / -1" } : null}>
      {label && <span className="trk-field__lab">{label}{hint && <small>{hint}</small>}</span>}
      {children}
    </label>
  );
}
function Input(props) {
  return <input {...props} className={"trk-input" + (props.className ? " " + props.className : "")} />;
}
function Select({ value, onChange, options, placeholder }) {
  return (
    <div className="trk-select">
      <select value={value} onChange={(e) => onChange(e.target.value)}>
        {placeholder != null && <option value="">{placeholder}</option>}
        {options.map((o) => {
          const val = typeof o === "string" ? o : o.value;
          const lab = typeof o === "string" ? o : o.label;
          return <option key={val} value={val}>{lab}</option>;
        })}
      </select>
      <Icon name="chevron" size={15} />
    </div>
  );
}

/* ---- Modal (centered dialog) ---- */
function Modal({ open, onClose, title, children, footer, width = 520 }) {
  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <Portal>
    <div className="trk-scrim" onMouseDown={onClose}>
      <div className="glass trk-modal" style={{ maxWidth: width }} onMouseDown={(e) => e.stopPropagation()}>
        {title && (
          <div className="trk-modal__head">
            <h3>{title}</h3>
            <button className="trk-iconbtn" onClick={onClose} aria-label="Close"><Icon name="close" size={17} /></button>
          </div>
        )}
        <div className="trk-modal__body">{children}</div>
        {footer && <div className="trk-modal__foot">{footer}</div>}
      </div>
    </div>
    </Portal>
  );
}

/* ---- Drawer (right slide-in, for the bet form) ---- */
function Drawer({ open, onClose, title, children, footer }) {
  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [open, onClose]);
  return (
    <Portal>
    <div className={"trk-drawer-root" + (open ? " is-open" : "")} aria-hidden={!open}>
      <div className="trk-scrim trk-scrim--drawer" onMouseDown={onClose}></div>
      <aside className="trk-drawer glass" role="dialog" aria-modal="true">
        <div className="trk-drawer__head">
          <h3>{title}</h3>
          <button className="trk-iconbtn" onClick={onClose} aria-label="Close"><Icon name="close" size={18} /></button>
        </div>
        <div className="trk-drawer__body">{children}</div>
        {footer && <div className="trk-drawer__foot">{footer}</div>}
      </aside>
    </div>
    </Portal>
  );
}

/* ---- Empty state ---- */
function EmptyState({ icon = "bets", title, sub, action }) {
  return (
    <div className="trk-empty">
      <div className="trk-empty__ph">
        <div className="trk-empty__icon"><Icon name={icon} size={26} /></div>
      </div>
      <div className="trk-empty__title">{title}</div>
      {sub && <div className="trk-empty__sub">{sub}</div>}
      {action && <div className="trk-empty__action">{action}</div>}
    </div>
  );
}

/* ---- striped placeholder (DS guidance for imagery) ---- */
function Placeholder({ label, height = 120 }) {
  return (
    <div className="trk-ph" style={{ height }}>
      <span className="trk-ph__mono">{label}</span>
    </div>
  );
}

Object.assign(window, {
  TrackerCtx, useTracker, Portal, Icon, Panel, Stat, SectionHead, Tag, ResultBadge,
  Segmented, Toggle, Btn, Field, Input, Select, Modal, Drawer, EmptyState, Placeholder
});
