/* GUIGKO App — interactive UI kit. All components accept handlers. */

// ---------- Button ----------
function Button({ children, kind = "primary", size = "md", onClick, icon, full, style = {}, disabled }) {
  const C = GK.colors;
  const [hover, setHover] = React.useState(false);
  const sizes = { sm: { p: "8px 14px", fs: 13, h: 34 }, md: { p: "11px 18px", fs: 14, h: 42 }, lg: { p: "14px 22px", fs: 15, h: 50 } };
  const s = sizes[size];
  const kinds = {
    primary: { bg: C.ink, fg: "#fff", bd: C.ink, hbg: "#1A2138" },
    flame:   { bg: C.flame, fg: "#fff", bd: C.flame, hbg: "#E64A12" },
    ghost:   { bg: "transparent", fg: C.ink, bd: C.ink + "30", hbg: C.ink + "0A" },
    light:   { bg: "#fff", fg: C.ink, bd: C.softLine, hbg: "#FBF8EE" },
    danger:  { bg: "#fff", fg: C.danger, bd: C.danger + "55", hbg: C.danger + "0D" },
  };
  const k = kinds[kind] || kinds.primary;
  return (
    <button onClick={disabled ? undefined : onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8,
        background: hover && !disabled ? k.hbg : k.bg, color: k.fg, border: `1px solid ${k.bd}`,
        padding: s.p, fontSize: s.fs, fontWeight: 500, height: s.h, borderRadius: 9,
        fontFamily: "'Geist', sans-serif", cursor: disabled ? "not-allowed" : "pointer",
        lineHeight: 1, whiteSpace: "nowrap", width: full ? "100%" : "auto",
        opacity: disabled ? 0.5 : 1, transition: "background .15s", ...style,
      }}>
      {icon && <span style={{ fontSize: s.fs + 2, lineHeight: 1 }}>{icon}</span>}
      {children}
    </button>
  );
}

// ---------- Pill ----------
function Pill({ children, tone = "neutral", style = {} }) {
  const C = GK.colors;
  const map = {
    neutral: { bg: "#0B0F1F0D", fg: C.ink, dot: C.slate },
    flame: { bg: "#FF5A1F1A", fg: "#C2410C", dot: C.flame },
    signal: { bg: "#0FB76B1A", fg: "#0A7E49", dot: C.signal },
    sky: { bg: "#3B6FF81A", fg: "#1D4ED8", dot: C.sky },
    danger: { bg: "#E11D481A", fg: C.danger, dot: C.danger },
    purple: { bg: "#A78BFA22", fg: "#6D28D9", dot: C.purple },
    ink: { bg: C.ink, fg: "#fff", dot: C.flame },
  };
  const s = map[tone] || map.neutral;
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, background: s.bg, color: s.fg,
      padding: "4px 10px", borderRadius: 999, fontSize: 12, fontWeight: 500, lineHeight: 1.3, whiteSpace: "nowrap", ...style }}>
      <span style={{ width: 6, height: 6, borderRadius: 999, background: s.dot }}></span>{children}
    </span>
  );
}

// ---------- Card ----------
function Card({ children, style = {}, dark = false, onClick, hover: hoverable }) {
  const C = GK.colors;
  const [h, setH] = React.useState(false);
  return (
    <div onClick={onClick} onMouseEnter={() => hoverable && setH(true)} onMouseLeave={() => hoverable && setH(false)}
      style={{
        background: dark ? C.ink : "#fff", color: dark ? "#fff" : C.ink,
        border: `1px solid ${dark ? "#1F2542" : C.softLine}`, borderRadius: 14, padding: 22,
        cursor: onClick ? "pointer" : "default",
        boxShadow: h ? "0 8px 28px rgba(11,15,31,0.10)" : "none",
        transform: h ? "translateY(-2px)" : "none", transition: "box-shadow .18s, transform .18s",
        ...style,
      }}>{children}</div>
  );
}

function Label({ children, color = GK.colors.slate, style = {} }) {
  return <div style={{ fontFamily: "'Geist Mono', monospace", fontSize: 10, letterSpacing: "0.18em",
    color, textTransform: "uppercase", ...style }}>{children}</div>;
}

// ---------- Input ----------
function Input({ label, value, onChange, placeholder, type = "text", right, suffix, style = {} }) {
  const C = GK.colors;
  const [focus, setFocus] = React.useState(false);
  return (
    <div style={{ marginBottom: 14, ...style }}>
      {label && <Label style={{ marginBottom: 6, fontSize: 10 }}>{label}</Label>}
      <div style={{ display: "flex", alignItems: "center", padding: "11px 13px", background: "#fff",
        border: `1.5px solid ${focus ? C.ink : C.softLine}`, borderRadius: 9, fontSize: 14, transition: "border .15s" }}>
        <input type={type} value={value} placeholder={placeholder}
          onChange={e => onChange && onChange(e.target.value)}
          onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
          style={{ flex: 1, border: "none", outline: "none", background: "transparent", fontSize: 14, fontFamily: "'Geist', sans-serif", color: C.ink, minWidth: 0 }}/>
        {suffix && <span style={{ color: C.slate, fontSize: 13, marginLeft: 8 }}>{suffix}</span>}
        {right}
      </div>
    </div>
  );
}

function Select({ label, value, onChange, options, style = {} }) {
  const C = GK.colors;
  return (
    <div style={{ marginBottom: 14, ...style }}>
      {label && <Label style={{ marginBottom: 6, fontSize: 10 }}>{label}</Label>}
      <div style={{ position: "relative" }}>
        <select value={value} onChange={e => onChange && onChange(e.target.value)}
          style={{ width: "100%", padding: "11px 13px", background: "#fff", border: `1.5px solid ${C.softLine}`,
            borderRadius: 9, fontSize: 14, fontFamily: "'Geist', sans-serif", color: C.ink, appearance: "none", cursor: "pointer" }}>
          {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
        </select>
        <span style={{ position: "absolute", right: 13, top: "50%", transform: "translateY(-50%)", pointerEvents: "none", color: C.slate }}>▾</span>
      </div>
    </div>
  );
}

// ---------- Modal ----------
function Modal({ open, onClose, title, children, width = 460 }) {
  const C = GK.colors;
  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, background: "rgba(11,15,31,0.45)", backdropFilter: "blur(3px)",
      zIndex: 9000, display: "grid", placeItems: "center", padding: 24, animation: "gkFadeIn .15s ease",
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width, maxWidth: "100%", maxHeight: "90vh", overflow: "auto", background: C.paper,
        borderRadius: 16, border: `1px solid ${C.softLine}`, boxShadow: "0 30px 80px rgba(0,0,0,0.3)",
        animation: "gkModalIn .2s ease",
      }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "20px 24px", borderBottom: `1px solid ${C.softLine}` }}>
          <h3 style={{ fontFamily: "'Instrument Serif', serif", fontSize: 26, fontWeight: 400, margin: 0, letterSpacing: "-0.02em" }}>{title}</h3>
          <button onClick={onClose} style={{ background: "transparent", border: "none", fontSize: 22, cursor: "pointer", color: C.slate, lineHeight: 1 }}>×</button>
        </div>
        <div style={{ padding: 24 }}>{children}</div>
      </div>
    </div>
  );
}

// ---------- Tabs (segmented) ----------
function Segmented({ options, value, onChange, size = "sm" }) {
  const C = GK.colors;
  return (
    <div style={{ display: "inline-flex", gap: 2, padding: 3, background: "#fff", border: `1px solid ${C.softLine}`, borderRadius: 8 }}>
      {options.map(o => (
        <button key={o.value} onClick={() => onChange(o.value)} style={{
          padding: size === "sm" ? "7px 14px" : "10px 18px", borderRadius: 6, border: "none", cursor: "pointer",
          background: value === o.value ? C.ink : "transparent", color: value === o.value ? "#fff" : C.slate,
          fontSize: 13, fontWeight: 500, fontFamily: "'Geist', sans-serif", whiteSpace: "nowrap", transition: "background .12s",
        }}>{o.label}</button>
      ))}
    </div>
  );
}

// ---------- Toggle ----------
function Toggle({ on, onChange }) {
  const C = GK.colors;
  return (
    <span onClick={() => onChange(!on)} style={{
      width: 36, height: 20, background: on ? C.flame : "#D8D0BC", borderRadius: 999, padding: 2,
      display: "inline-flex", justifyContent: on ? "flex-end" : "flex-start", cursor: "pointer", transition: "background .18s", flexShrink: 0,
    }}>
      <span style={{ width: 16, height: 16, background: "#fff", borderRadius: 999, transition: "all .18s", boxShadow: "0 1px 2px rgba(0,0,0,0.2)" }}/>
    </span>
  );
}

// ---------- Avatar ----------
function Avatar({ name = "?", size = 36, tone = 0, style = {} }) {
  const tones = [["#FFE4D6","#B43A0A"],["#D9EFE3","#0A6E45"],["#DCE4F8","#1A3DA8"],["#F0E6D2","#5A4515"],["#E9D9F8","#5A1A8C"]];
  const [bg, fg] = tones[tone % tones.length];
  const initials = name.split(/\s+/).map(s => s[0]).filter(Boolean).slice(0, 2).join("").toUpperCase();
  return <div style={{ width: size, height: size, borderRadius: Math.max(6, size * 0.22), background: bg, color: fg,
    display: "grid", placeItems: "center", fontFamily: "'Geist', sans-serif", fontWeight: 600, fontSize: size * 0.4, flexShrink: 0, ...style }}>{initials}</div>;
}

// ---------- Charts ----------
function SparkLine({ data = [], color = GK.colors.flame, width = 220, height = 56, fill = true }) {
  if (!data.length) return null;
  const max = Math.max(...data), min = Math.min(...data), range = max - min || 1;
  const pts = data.map((v, i) => [(i / (data.length - 1)) * width, height - ((v - min) / range) * (height - 10) - 5]);
  const path = pts.map((p, i) => `${i === 0 ? "M" : "L"} ${p[0]},${p[1]}`).join(" ");
  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} style={{ display: "block", maxWidth: "100%" }}>
      {fill && <path d={path + ` L ${width},${height} L 0,${height} Z`} fill={color} opacity="0.10"/>}
      <path d={path} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="3.5" fill={color}/>
    </svg>
  );
}

function BarChart({ data = [], width = 360, height = 160, color = GK.colors.ink, accent = GK.colors.flame, accentIndex = -1 }) {
  const max = Math.max(...data.map(d => d.v)) || 1;
  const barW = width / data.length - 8;
  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} style={{ display: "block", maxWidth: "100%" }}>
      {data.map((d, i) => {
        const h = (d.v / max) * (height - 28), x = i * (barW + 8), y = height - h - 22;
        return (
          <g key={i}>
            <rect x={x} y={y} width={barW} height={h} fill={i === accentIndex ? accent : color} rx="2"/>
            <text x={x + barW/2} y={height - 6} fontFamily="'Geist Mono', monospace" fontSize="10" fill={GK.colors.slate} textAnchor="middle">{d.l}</text>
          </g>
        );
      })}
    </svg>
  );
}

function Donut({ segments = [], size = 160, thickness = 22, track = "#F0EBDC" }) {
  const total = segments.reduce((s, x) => s + x.v, 0) || 1;
  const r = (size - thickness) / 2, cx = size / 2, cy = size / 2, circ = 2 * Math.PI * r;
  let offset = 0;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ display: "block" }}>
      <circle cx={cx} cy={cy} r={r} fill="none" stroke={track} strokeWidth={thickness}/>
      {segments.map((seg, i) => {
        const len = (seg.v / total) * circ;
        const el = <circle key={i} cx={cx} cy={cy} r={r} fill="none" stroke={seg.c} strokeWidth={thickness}
          strokeDasharray={`${len} ${circ - len}`} strokeDashoffset={-offset} transform={`rotate(-90 ${cx} ${cy})`}/>;
        offset += len;
        return el;
      })}
    </svg>
  );
}

// ---------- Vehicle image placeholder ----------
function CarImg({ width, height, label = "", tone = "warm" }) {
  const C = GK.colors;
  const bg = tone === "ink" ? C.ink : "#E6DDC9";
  const fg = tone === "ink" ? "#FFFFFF55" : "#0B0F1F40";
  const pid = "carp-" + Math.random().toString(36).slice(2, 7);
  return (
    <div style={{ width, height, background: bg, position: "relative", overflow: "hidden", color: fg,
      fontFamily: "'Geist Mono', monospace", display: "grid", placeItems: "center", fontSize: 11, letterSpacing: "0.16em" }}>
      <svg width="100%" height="100%" style={{ position: "absolute", inset: 0 }}>
        <defs><pattern id={pid} width="16" height="16" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
          <line x1="0" y1="0" x2="0" y2="16" stroke={tone === "ink" ? "#FFFFFF10" : "#0B0F1F0A"} strokeWidth="7"/>
        </pattern></defs>
        <rect width="100%" height="100%" fill={`url(#${pid})`}/>
        {/* simple car silhouette */}
        <g transform={`translate(${typeof width === "number" ? width/2 : 60}, ${(typeof height === "number" ? height : 100)/2})`} opacity="0.5">
          <path d="M -34 6 L -28 -6 L 14 -6 L 24 4 L 34 6 L 34 14 L -34 14 Z" fill={tone === "ink" ? "#FFFFFF22" : "#0B0F1F18"}/>
          <circle cx="-20" cy="14" r="6" fill={tone === "ink" ? "#FFFFFF33" : "#0B0F1F28"}/>
          <circle cx="20" cy="14" r="6" fill={tone === "ink" ? "#FFFFFF33" : "#0B0F1F28"}/>
        </g>
      </svg>
      {label && <span style={{ position: "relative", textTransform: "uppercase", fontWeight: 600 }}>{label}</span>}
    </div>
  );
}

// ---------- Empty / progress bar ----------
function Bar({ pct, color = GK.colors.flame, track = "#F0EBDC", h = 8 }) {
  return <div style={{ height: h, background: track, borderRadius: h/2, overflow: "hidden" }}>
    <div style={{ width: `${Math.min(100, pct)}%`, height: "100%", background: color, borderRadius: h/2, transition: "width .4s ease" }}/>
  </div>;
}

Object.assign(window, {
  Button, Pill, Card, Label, Input, Select, Modal, Segmented, Toggle, Avatar,
  SparkLine, BarChart, Donut, CarImg, Bar,
});
