// Shared components
const { useState, useEffect, useMemo, useRef } = React;

function fmt(n, dp = 0) {
  return new Intl.NumberFormat("en-US", { minimumFractionDigits: dp, maximumFractionDigits: dp }).format(n);
}
function sar(n, dp = 2) {
  return fmt(n, dp);
}

function Pill({ kind = "soft", dot, children }) {
  return (
    <span className={`pill pill-${kind}`}>
      {dot && <span className="dot" />}
      {children}
    </span>
  );
}

function Card({ title, titleEn, action, children, className = "", style }) {
  return (
    <div className={`card ${className}`} style={style}>
      {(title || action) && (
        <div className="card-hd">
          {title && <h3 className="card-title">{title}{titleEn && <span className="en">{titleEn}</span>}</h3>}
          {action && <div>{action}</div>}
        </div>
      )}
      {children}
    </div>
  );
}

function Sparkline({ data, color = "var(--ink)", h = 40, w = 120 }) {
  const max = Math.max(...data), min = Math.min(...data);
  const range = max - min || 1;
  const pts = data.map((v, i) => `${(i / (data.length - 1)) * w},${h - ((v - min) / range) * (h - 4) - 2}`).join(" ");
  return (
    <svg className="sparkline" width={w} height={h} viewBox={`0 0 ${w} ${h}`}>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={(w)} cy={h - ((data[data.length-1] - min) / range) * (h - 4) - 2} r="2.5" fill={color} />
    </svg>
  );
}

// Fake QR — a deterministic SVG grid based on a seed string
function FauxQR({ seed = "ZATCA" }) {
  const size = 21;
  const cells = useMemo(() => {
    let h = 0;
    for (let i = 0; i < seed.length; i++) h = (h * 31 + seed.charCodeAt(i)) >>> 0;
    const rand = () => {
      h = (h * 1103515245 + 12345) >>> 0;
      return h / 0xFFFFFFFF;
    };
    const grid = [];
    for (let y = 0; y < size; y++) {
      const row = [];
      for (let x = 0; x < size; x++) {
        // finder patterns
        const inFinder =
          (x < 7 && y < 7) || (x >= size - 7 && y < 7) || (x < 7 && y >= size - 7);
        if (inFinder) {
          const fx = x >= size - 7 ? x - (size - 7) : x;
          const fy = y >= size - 7 ? y - (size - 7) : y;
          const ring = (fx === 0 || fx === 6 || fy === 0 || fy === 6);
          const mid = fx >= 2 && fx <= 4 && fy >= 2 && fy <= 4;
          row.push(ring || mid ? 1 : 0);
        } else {
          row.push(rand() > 0.52 ? 1 : 0);
        }
      }
      grid.push(row);
    }
    return grid;
  }, [seed]);
  return (
    <svg viewBox={`0 0 ${size} ${size}`} shapeRendering="crispEdges">
      {cells.map((row, y) => row.map((v, x) => v ? <rect key={`${x}-${y}`} x={x} y={y} width="1" height="1" fill="#0B3D2E" /> : null))}
    </svg>
  );
}

function SegControl({ value, onChange, options }) {
  return (
    <div className="seg">
      {options.map(o => (
        <button key={o.value} className={value === o.value ? "active" : ""} onClick={() => onChange(o.value)}>{o.label}</button>
      ))}
    </div>
  );
}

function ProgressBar({ value, max = 100, tone = "ink" }) {
  return (
    <div className="progress">
      <div className={`progress-bar ${tone}`} style={{ width: `${Math.min(100, (value/max)*100)}%` }} />
    </div>
  );
}

Object.assign(window, { fmt, sar, Pill, Card, Sparkline, FauxQR, SegControl, ProgressBar });
