/* Shared UI primitives + charts. */
const { useState, useEffect, useMemo, useRef } = React;

/* ---------- Tiny helpers ---------- */
const fmtINR = (n, opts = {}) => {
  if (n == null || isNaN(n)) return "—";
  const { compact = false } = opts;
  if (compact && Math.abs(n) >= 10000000) return "₹" + (n/10000000).toFixed(2) + "Cr";
  if (compact && Math.abs(n) >= 100000) return "₹" + (n/100000).toFixed(2) + "L";
  if (compact && Math.abs(n) >= 1000) return "₹" + (n/1000).toFixed(1) + "K";
  return "₹" + Math.round(n).toLocaleString("en-IN");
};
const fmtNum = (n, d=0) => n==null ? "—" : Number(n).toLocaleString("en-IN", { minimumFractionDigits:d, maximumFractionDigits:d });
const fmtPct = (n, d=1) => n==null ? "—" : (Number(n)*100).toFixed(d) + "%";
const fmtDate = (s) => {
  if (!s) return "—";
  const d = new Date(s);
  return d.toLocaleDateString("en-GB", { day:"2-digit", month:"short", year:"numeric" });
};
/* Proxy calls: localhost proxy in dev; on the hosted demo __PROXY_URL is null and
   the buttons report that the live Vue.ai proxy isn't connected. */
const proxyFetch = (path, opts) => {
  const base = window.__PROXY_URL === null ? null : (window.__PROXY_URL || "http://localhost:8001");
  if (!base) return Promise.reject(new Error("Live Vue.ai proxy isn't connected in this hosted demo"));
  return fetch(base + path, opts);
};
window.proxyFetch = proxyFetch;
window.fmtINR = fmtINR; window.fmtNum = fmtNum; window.fmtPct = fmtPct; window.fmtDate = fmtDate;

/* ---------- Severity Pill ---------- */
function Pill({ severity, children, size }) {
  const map = {
    POSITIVE: "pill--pos", WARNING:"pill--warn", NEGATIVE:"pill--neg",
    INFO:"pill--info", ACTION:"pill--action", CAUTION:"pill--warn", NEUTRAL:"pill--neutral"
  };
  return <span className={`pill ${map[severity]||"pill--neutral"}`} style={size==="lg"?{height:22, padding:"0 9px"}:{}}>{children}</span>;
}

/* ---------- Card ---------- */
function Card({ title, subtitle, actions, children, style, padded = true, tight = false }) {
  return (
    <div style={{
      background: "var(--window)",
      borderRadius: "var(--r-inner)",
      boxShadow: "0 0 0 1px var(--separator)",
      ...style
    }}>
      {(title || actions) && (
        <div style={{
          display:"flex", alignItems:"center", justifyContent:"space-between",
          padding: tight ? "8px 12px" : "10px 14px",
          borderBottom: "1px solid var(--divider)"
        }}>
          <div>
            {title && <div style={{font:"700 13px/16px var(--font)", color:"var(--label-1)"}}>{title}</div>}
            {subtitle && <div style={{font:"400 11px/14px var(--font)", color:"var(--label-2)", marginTop:2}}>{subtitle}</div>}
          </div>
          <div style={{display:"flex", gap:6, alignItems:"center"}}>{actions}</div>
        </div>
      )}
      <div style={{padding: padded ? (tight ? "10px 12px" : "12px 14px") : 0}}>{children}</div>
    </div>
  );
}

/* ---------- Stat row ---------- */
function Stat({ label, value, sub, align="left", mono=true }) {
  return (
    <div style={{textAlign:align, minWidth:0}}>
      <div className="eyebrow" style={{marginBottom:4}}>{label}</div>
      <div className={mono?"num":""} style={{font:"600 15px/20px var(--font)", color:"var(--label-1)", whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis"}}>{value}</div>
      {sub && <div style={{font:"400 11px/14px var(--font)", color:"var(--label-2)", marginTop:2}}>{sub}</div>}
    </div>
  );
}

/* ---------- Credit Score Gauge (semi-circular) ---------- */
function CreditGauge({ score = 0, min = 300, max = 900, size = 180, band }) {
  // Map score to angle from -90° (left) to 90° (right), 180° sweep
  const pct = Math.max(0, Math.min(1, (score - min) / (max - min)));
  const angle = -90 + pct * 180;
  const r = size/2 - 14;
  const cx = size/2, cy = size/2 + 4;

  // Band colors
  const bands = [
    { t: 0.00, c: "var(--neg)"  },   // 300-580
    { t: 0.47, c: "var(--warn)" },   // 580-680
    { t: 0.63, c: "var(--info)" },   // 680-750
    { t: 0.75, c: "var(--pos)"  }    // 750+
  ];

  const arc = (t0, t1, color) => {
    const a0 = -90 + t0*180;
    const a1 = -90 + t1*180;
    const rad = a => (a * Math.PI)/180;
    const x0 = cx + r*Math.cos(rad(a0));
    const y0 = cy + r*Math.sin(rad(a0));
    const x1 = cx + r*Math.cos(rad(a1));
    const y1 = cy + r*Math.sin(rad(a1));
    const large = (t1-t0) > 0.5 ? 1 : 0;
    return <path key={a0} d={`M ${x0} ${y0} A ${r} ${r} 0 ${large} 1 ${x1} ${y1}`}
      stroke={color} strokeWidth="10" fill="none" strokeLinecap="butt" />;
  };

  const rad = a => (a*Math.PI)/180;
  const nx = cx + r*Math.cos(rad(angle));
  const ny = cy + r*Math.sin(rad(angle));

  return (
    <div style={{display:"flex", flexDirection:"column", alignItems:"center"}}>
      <svg width={size} height={size/2 + 24} style={{overflow:"visible"}}>
        {/* Track segments */}
        {arc(0.00, 0.46, "var(--neg)")}
        {arc(0.47, 0.62, "var(--warn)")}
        {arc(0.63, 0.74, "var(--info)")}
        {arc(0.75, 1.00, "var(--pos)")}
        {/* Needle */}
        <line x1={cx} y1={cy} x2={nx} y2={ny} stroke="var(--ink)" strokeWidth="2" />
        <circle cx={cx} cy={cy} r="5" fill="var(--ink)" />
        {/* ticks */}
        {[0, 0.25, 0.5, 0.75, 1].map((t,i)=>{
          const a = -90 + t*180;
          const x1t = cx + (r+2)*Math.cos(rad(a));
          const y1t = cy + (r+2)*Math.sin(rad(a));
          const x2t = cx + (r+8)*Math.cos(rad(a));
          const y2t = cy + (r+8)*Math.sin(rad(a));
          return <line key={i} x1={x1t} y1={y1t} x2={x2t} y2={y2t} stroke="var(--ink-4)" strokeWidth="1" />;
        })}
      </svg>
      <div style={{display:"flex", alignItems:"baseline", gap:6, marginTop:-10}}>
        <span className="num" style={{font:"600 28px/32px var(--font-display)", letterSpacing:"-0.02em"}}>{score}</span>
        <span style={{fontSize:11, color:"var(--ink-3)"}}>/ {max}</span>
      </div>
      {band && <div style={{marginTop:4}}><Pill severity={band==="high"?"POSITIVE":band==="mid"?"INFO":"WARNING"}>{band} band</Pill></div>}
    </div>
  );
}

/* ---------- Ring chart (utilization / FOIR / payment ratio) ---------- */
function RingChart({ value = 0, max = 1, size = 88, stroke = 9, color = "var(--ring-1)", label, sublabel, tone }) {
  const pct = Math.max(0, Math.min(1, value/max));
  const r = (size - stroke)/2;
  const c = 2*Math.PI*r;
  const dash = c * pct;
  return (
    <div style={{display:"flex", alignItems:"center", gap:12}}>
      <svg width={size} height={size}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--surface-3)" strokeWidth={stroke} />
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={color} strokeWidth={stroke}
          strokeDasharray={`${dash} ${c-dash}`} strokeDashoffset={c*0.25} strokeLinecap="round"
          transform={`rotate(-90 ${size/2} ${size/2})`} />
        <text x={size/2} y={size/2+1} textAnchor="middle" dominantBaseline="middle"
          style={{font:"600 15px var(--font)", fontVariantNumeric:"tabular-nums", fill:"var(--label-1)"}}>
          {(pct*100).toFixed(0)}%
        </text>
      </svg>
      <div>
        <div style={{font:"600 12px/15px var(--font)", color:"var(--label-1)"}}>{label}</div>
        {sublabel && <div style={{font:"400 11px/14px var(--font)", color:"var(--label-2)", marginTop:2}}>{sublabel}</div>}
        {tone && <div style={{marginTop:4}}><Pill severity={tone.severity}>{tone.label}</Pill></div>}
      </div>
    </div>
  );
}

/* ---------- Bar (horizontal, simple) ---------- */
function Bar({ value = 0, max = 1, color = "var(--brand)", height = 6 }) {
  const pct = Math.max(0, Math.min(1, value/max)) * 100;
  return (
    <div style={{height, background:"var(--fill-2)", borderRadius:"var(--r-pill)", overflow:"hidden"}}>
      <div style={{width: pct+"%", height:"100%", background: color, borderRadius:"inherit"}} />
    </div>
  );
}

/* ---------- Simple slider ---------- */
function Slider({ value, min, max, step=1, onChange, fmt, width }) {
  return (
    <div style={{display:"flex", flexDirection:"column", gap:4, width: width||"100%"}}>
      <input type="range" className="slider" min={min} max={max} step={step} value={value}
        onChange={e => onChange(Number(e.target.value))}
        style={{"--v": (max>min ? ((value-min)/(max-min))*100 : 0) + "%"}} />
      <div className="num" style={{display:"flex", justifyContent:"space-between", font:"400 10px/13px var(--font)", color:"var(--label-2)"}}>
        <span>{fmt?fmt(min):min}</span>
        <span>{fmt?fmt(max):max}</span>
      </div>
    </div>
  );
}

/* ---------- Button (M2P Glass: fills, not borders) ---------- */
const BTN_VARIANT = { default:"", primary:"primary", accent:"tinted", tinted:"tinted", ghost:"plain", plain:"plain", danger:"danger", success:"success" };
const BTN_SIZE = { xs:"mn", sm:"sm", md:"", lg:"lg", xl:"xl" };
function Btn({ variant="default", size="md", children, onClick, disabled, style, icon, title }) {
  const cls = ["btn", BTN_VARIANT[variant] ?? "", BTN_SIZE[size] ?? ""].filter(Boolean).join(" ");
  return (
    <button type="button" className={cls} onClick={onClick} disabled={disabled} title={title} style={style}>
      {icon && <span style={{display:"inline-flex"}}>{icon}</span>}
      {children}
    </button>
  );
}

/* ---------- Icon set (minimal strokes, original) ---------- */
const Icon = {
  search:(p)=>svgI("M11 11l3 3 M11 11a4 4 0 1 0-5.656-5.656 4 4 0 0 0 5.656 5.656z",p),
  user:(p)=>svgI("M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6z M2 14c0-3 2.5-5 6-5s6 2 6 5",p),
  home:(p)=>svgI("M2 7l6-5 6 5v7H2z M6 14v-4h4v4",p),
  history:(p)=>svgI("M8 3v5l3 2 M3 8a5 5 0 1 0 1.5-3.5 M3 3v2h2",p),
  wallet:(p)=>svgI("M2 5h10v7H2z M2 5V3h9v2 M10 8.5h1",p),
  id:(p)=>svgI("M2 4h12v8H2z M5 7.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3z M5 10c-1 0-2 .5-2 1.5 M9 6h3 M9 8h3 M9 10h2",p),
  spark:(p)=>svgI("M8 2l1.5 3.5L13 7l-3.5 1.5L8 12l-1.5-3.5L3 7l3.5-1.5z M13 11l.8 1.8L15 13l-1.2.2L13 15l-.8-1.8L11 13l1.2-.2z",p),
  arrow:(p)=>svgI("M3 8h10 M9 4l4 4-4 4",p),
  check:(p)=>svgI("M3 8l3 3 7-7",p),
  x:(p)=>svgI("M3 3l10 10 M13 3L3 13",p),
  dot:(p)=>svgI("M8 8m-2 0a2 2 0 1 0 4 0 2 2 0 1 0-4 0",p),
  filter:(p)=>svgI("M2 3h12 M4 7h8 M6 11h4",p),
  bell:(p)=>svgI("M4 11V7a4 4 0 1 1 8 0v4 M3 11h10 M6.5 13h3",p),
  plus:(p)=>svgI("M8 3v10 M3 8h10",p),
  phone:(p)=>svgI("M3 3l2 .5 1 3-1.5 1a7 7 0 0 0 4 4l1-1.5 3 1L13 13a10 10 0 0 1-10-10z",p),
  mail:(p)=>svgI("M2 4h12v8H2z M2 4l6 4 6-4",p),
  chevron:(p)=>svgI("M5 3l4 5-4 5",p),
  download:(p)=>svgI("M8 2v8 M4 7l4 4 4-4 M3 13h10",p),
  moon:(p)=>svgI("M12 9a5 5 0 1 1-5-7 4 4 0 0 0 5 7z",p),
  sun:(p)=>svgI("M8 3V1 M8 15v-2 M3 8H1 M15 8h-2 M3.5 3.5l1.5 1.5 M11 11l1.5 1.5 M3.5 12.5L5 11 M11 5l1.5-1.5 M8 11.5a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7z",p),
};
function svgI(d, {size=14, stroke="currentColor", strokeWidth=1.6}={}){
  return <svg width={size} height={size} viewBox="0 0 16 16" fill="none" stroke={stroke} strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round">
    <path d={d}/>
  </svg>;
}

/* ---------- Persona tag ---------- */
function PersonaTag({ name, cluster }) {
  return (
    <div style={{
      display:"inline-flex", alignItems:"center", gap:8,
      padding:"6px 10px", borderRadius: "var(--r-tile)",
      background:"var(--fill-4)",
      fontSize: 12
    }}>
      <span style={{
        width:24, height:24, borderRadius:"var(--r-rg)", display:"inline-flex",
        alignItems:"center", justifyContent:"center",
        background:"var(--accent-tint)", color:"var(--accent)", fontWeight:700,
        fontSize:11, fontVariantNumeric:"tabular-nums"
      }}>C{cluster}</span>
      <div>
        <div className="eyebrow" style={{fontSize:10, lineHeight:"13px"}}>Persona · Cluster {cluster}</div>
        <div style={{fontWeight:600, color:"var(--label-1)", fontSize:12}}>{name}</div>
      </div>
    </div>
  );
}

Object.assign(window, { Pill, Card, Stat, CreditGauge, RingChart, Bar, Slider, Btn, Icon, PersonaTag });
