// Vecton primitives + icons for Voice-to-Form
const V = {
  orange: "#FF5631", purple: "#7E43BA", brown: "#24140D",
  beige: "#E8E9D7", offWhite: "#F9FAF6", white: "#FFFFFF",
  brownLight: "#3D2A1F", brownMid: "#6B5147", brownFaded: "#9A8A82",
  orangeSubtle: "rgba(255,86,49,0.08)", orangeLight: "rgba(255,86,49,0.15)",
  purpleSubtle: "rgba(126,67,186,0.08)", purpleLight: "rgba(126,67,186,0.15)",
  borderLight: "rgba(36,20,13,0.10)", borderMed: "rgba(36,20,13,0.14)",
  success: "#16A34A", successBg: "rgba(22,163,74,0.10)",
  warning: "#D97706", warningBg: "rgba(217,119,6,0.12)",
  danger: "#DC2626", dangerBg: "rgba(220,38,38,0.10)",
  radius: "7px", radiusSm: "5px", radiusLg: "11px", radiusPill: "9999px",
  font: "'Instrument Sans', Arial, sans-serif",
  fw: { r: 400, m: 500, sb: 600 },
  shadowSm: "0 1px 2px rgba(36,20,13,.08)",
  shadowMd: "0 4px 12px rgba(36,20,13,.10)",
  shadowLg: "0 12px 32px rgba(36,20,13,.15)",
  shadowOrange: "0 4px 16px rgba(255,86,49,.25)",
};

// Lucide-style stroke icons (1.5px, round caps)
const Icon = ({ name, size = 16, color = "currentColor", sw = 1.5, style }) => {
  const p = {
    width: size, height: size, viewBox: "0 0 24 24", fill: "none",
    stroke: color, strokeWidth: sw, strokeLinecap: "round", strokeLinejoin: "round",
    style: { display: "block", flexShrink: 0, ...style },
  };
  const paths = {
    mic: <><rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 10a7 7 0 0 0 14 0"/><line x1="12" y1="19" x2="12" y2="22"/></>,
    micOff: <><line x1="2" y1="2" x2="22" y2="22"/><path d="M18.89 13.23A7.12 7.12 0 0 0 19 12v-2"/><path d="M5 10v2a7 7 0 0 0 12 5"/><path d="M15 9.34V5a3 3 0 0 0-5.68-1.33"/><path d="M9 9v3a3 3 0 0 0 5.12 2.12"/><line x1="12" y1="19" x2="12" y2="22"/></>,
    upload: <><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></>,
    play: <polygon points="6 4 20 12 6 20 6 4"/>,
    pause: <><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></>,
    stop: <rect x="5" y="5" width="14" height="14" rx="1"/>,
    check: <path d="M20 6L9 17l-5-5"/>,
    checkCircle: <><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></>,
    x: <><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></>,
    arrowRight: <><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></>,
    arrowLeft: <><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 19"/></>,
    alert: <><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></>,
    info: <><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></>,
    sparkles: <><path d="M12 3v4M12 17v4M3 12h4M17 12h4M5.6 5.6l2.8 2.8M15.6 15.6l2.8 2.8M5.6 18.4l2.8-2.8M15.6 8.4l2.8-2.8"/></>,
    user: <><path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></>,
    briefcase: <><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16"/></>,
    file: <><path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><polyline points="13 2 13 9 20 9"/></>,
    edit: <><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></>,
    trash: <><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></>,
    zap: <path d="M13 2L3 14h9l-1 10 10-12h-9l1-10z"/>,
    refresh: <><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></>,
    download: <><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></>,
    phone: <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.127.96.361 1.903.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0 1 22 16.92z"/>,
    mail: <><rect x="2" y="4" width="20" height="16" rx="2"/><polyline points="22 7 12 13 2 7"/></>,
    home: <><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></>,
    creditCard: <><rect x="1" y="4" width="22" height="16" rx="2"/><line x1="1" y1="10" x2="23" y2="10"/></>,
    coins: <><circle cx="8" cy="8" r="6"/><path d="M18.09 10.37A6 6 0 1 1 10.34 18"/><path d="M7 6h1v4"/><path d="M16.71 13.88l.7.71-2.82 2.82"/></>,
    shield: <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>,
    lock: <><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></>,
    hash: <><line x1="4" y1="9" x2="20" y2="9"/><line x1="4" y1="15" x2="20" y2="15"/><line x1="10" y1="3" x2="8" y2="21"/><line x1="16" y1="3" x2="14" y2="21"/></>,
    circle: <circle cx="12" cy="12" r="10"/>,
    chevDown: <path d="M6 9l6 6 6-6"/>,
    chevUp: <path d="M18 15l-6-6-6 6"/>,
    volume: <><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/></>,
    eye: <><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></>,
    wand: <><path d="M15 4V2M15 16v-2M8 9h2M20 9h2M17.8 11.8L19 13M15 9h0M17.8 6.2L19 5M3 21l9-9M12.2 6.2L11 5"/></>,
    clock: <><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></>,
    building: <><rect x="4" y="2" width="16" height="20" rx="1"/><path d="M9 22v-4h6v4"/><path d="M8 6h.01M16 6h.01M12 6h.01M12 10h.01M12 14h.01M16 10h.01M16 14h.01M8 10h.01M8 14h.01"/></>,
    trendingUp: <><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></>,
    waveform: <><line x1="2" y1="12" x2="2" y2="12"/><line x1="6" y1="8" x2="6" y2="16"/><line x1="10" y1="4" x2="10" y2="20"/><line x1="14" y1="10" x2="14" y2="14"/><line x1="18" y1="6" x2="18" y2="18"/><line x1="22" y1="12" x2="22" y2="12"/></>,
  };
  return <svg {...p}>{paths[name]}</svg>;
};

const Button = ({ variant = "primary", size = "md", icon, iconRight, children, onClick, disabled, style, type = "button" }) => {
  const sizes = {
    sm: { padding: "7px 12px", fontSize: 12, gap: 6 },
    md: { padding: "10px 18px", fontSize: 13, gap: 8 },
    lg: { padding: "13px 24px", fontSize: 14, gap: 10 },
  };
  const variants = {
    primary: { background: V.orange, color: V.offWhite, border: "none", boxShadow: V.shadowOrange },
    secondary: { background: V.brown, color: V.beige, border: "none" },
    outline: { background: V.white, color: V.brown, border: `1px solid ${V.borderMed}` },
    ghost: { background: "transparent", color: V.brownMid, border: "none", boxShadow: "none" },
  };
  return (
    <button onClick={onClick} type={type} disabled={disabled} style={{
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      fontFamily: V.font, fontWeight: V.fw.m, borderRadius: V.radius,
      cursor: disabled ? "not-allowed" : "pointer",
      opacity: disabled ? 0.5 : 1,
      transition: "transform 0.15s ease, box-shadow 0.15s ease, background 0.15s ease",
      ...sizes[size], ...variants[variant], ...style,
    }}
    onMouseEnter={e => { if (!disabled) e.currentTarget.style.transform = "translateY(-1px)"; }}
    onMouseLeave={e => { e.currentTarget.style.transform = "translateY(0)"; }}
    >
      {icon && <Icon name={icon} size={size === "sm" ? 12 : size === "lg" ? 15 : 14} color="currentColor"/>}
      {children}
      {iconRight && <Icon name={iconRight} size={size === "sm" ? 12 : size === "lg" ? 15 : 14} color="currentColor"/>}
    </button>
  );
};

const Eyebrow = ({ children, style }) => (
  <div style={{
    fontFamily: V.font, fontSize: 11, fontWeight: V.fw.m, color: V.orange,
    textTransform: "uppercase", letterSpacing: "0.12em", ...style,
  }}>{children}</div>
);

const FocusCorners = ({ color = V.orange, size = 10, thick = 1.5, inset = -4 }) => {
  const s = { position: "absolute", width: size, height: size, pointerEvents: "none" };
  return (
    <>
      <div style={{ ...s, top: inset, left: inset, borderTop: `${thick}px solid ${color}`, borderLeft: `${thick}px solid ${color}` }}/>
      <div style={{ ...s, top: inset, right: inset, borderTop: `${thick}px solid ${color}`, borderRight: `${thick}px solid ${color}` }}/>
      <div style={{ ...s, bottom: inset, left: inset, borderBottom: `${thick}px solid ${color}`, borderLeft: `${thick}px solid ${color}` }}/>
      <div style={{ ...s, bottom: inset, right: inset, borderBottom: `${thick}px solid ${color}`, borderRight: `${thick}px solid ${color}` }}/>
    </>
  );
};

// Confidence badge with color-coded dot + %
const ConfidenceBadge = ({ score }) => {
  // score 0..1
  let color, bg, label;
  if (score >= 0.9)      { color = V.success; bg = V.successBg; label = "High"; }
  else if (score >= 0.7) { color = V.warning; bg = V.warningBg; label = "Med";  }
  else                   { color = V.danger;  bg = V.dangerBg;  label = "Low";  }
  const pct = Math.round(score * 100);
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 5,
      fontFamily: V.font, fontSize: 10, fontWeight: V.fw.sb,
      padding: "2px 7px 2px 6px", borderRadius: V.radiusPill,
      background: bg, color, fontVariantNumeric: "tabular-nums",
      whiteSpace: "nowrap",
    }}>
      <span style={{ width: 5, height: 5, borderRadius: "50%", background: color }}/>
      {pct}%
    </span>
  );
};

// Status pill
const StatusPill = ({ kind = "neutral", children, icon }) => {
  const map = {
    success: { bg: V.successBg, fg: V.success },
    warning: { bg: V.warningBg, fg: V.warning },
    danger:  { bg: V.dangerBg,  fg: V.danger  },
    info:    { bg: V.purpleSubtle, fg: V.purple },
    accent:  { bg: V.orangeSubtle, fg: V.orange },
    neutral: { bg: "rgba(36,20,13,.06)", fg: V.brownMid },
  };
  const s = map[kind] || map.neutral;
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6,
      fontFamily: V.font, fontSize: 11, fontWeight: V.fw.m,
      padding: "4px 10px", borderRadius: V.radiusPill,
      background: s.bg, color: s.fg, whiteSpace: "nowrap",
    }}>
      {icon && <Icon name={icon} size={11} color={s.fg}/>}
      {children}
    </span>
  );
};

// Input field with optional confidence badge + status border
const FormField = ({
  label, value, onChange, placeholder, confidence, status, note, error, icon,
  type = "text", options, monospace, mask, readOnly, required,
}) => {
  // status: "filled" | "missing" | "low" | "corrected" | "spelled" | null
  const statusColors = {
    filled:    { border: V.borderMed,   bg: V.white },
    missing:   { border: V.danger,      bg: V.dangerBg },
    low:       { border: V.warning,     bg: "rgba(217,119,6,0.04)" },
    corrected: { border: V.purple,      bg: V.purpleSubtle },
    spelled:   { border: V.purple,      bg: V.purpleSubtle },
    empty:     { border: V.borderMed,   bg: V.white },
  };
  const sc = statusColors[status] || statusColors.empty;
  const isFilled = value !== null && value !== undefined && value !== "";

  return (
    <div style={{ fontFamily: V.font }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 6, minHeight: 18 }}>
        <label style={{ fontSize: 11, fontWeight: V.fw.m, color: V.brownMid, display: "inline-flex", alignItems: "center", gap: 6 }}>
          {label}
          {required && <span style={{ color: V.orange }}>*</span>}
        </label>
        {confidence !== undefined && confidence !== null && isFilled && <ConfidenceBadge score={confidence}/>}
      </div>
      <div style={{ position: "relative" }}>
        {icon && (
          <div style={{ position: "absolute", left: 11, top: "50%", transform: "translateY(-50%)", zIndex: 1 }}>
            <Icon name={icon} size={13} color={V.brownFaded}/>
          </div>
        )}
        {options ? (
          <select value={value ?? ""} onChange={e => onChange?.(e.target.value)} disabled={readOnly}
            style={{
              width: "100%", padding: icon ? "10px 12px 10px 32px" : "10px 12px",
              borderRadius: V.radiusSm, border: `1px solid ${sc.border}`,
              fontFamily: V.font, fontSize: 13, color: isFilled ? V.brown : V.brownFaded,
              background: sc.bg, outline: "none", boxSizing: "border-box",
              cursor: readOnly ? "default" : "pointer",
              appearance: "none", backgroundImage: `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%239A8A82' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'><path d='M6 9l6 6 6-6'/></svg>")`,
              backgroundRepeat: "no-repeat", backgroundPosition: "right 12px center",
              paddingRight: 32,
            }}>
            <option value="">{placeholder || "— Select —"}</option>
            {options.map(o => <option key={o} value={o}>{o}</option>)}
          </select>
        ) : (
          <input
            type={type}
            value={value ?? ""}
            onChange={e => onChange?.(e.target.value)}
            placeholder={placeholder}
            readOnly={readOnly}
            style={{
              width: "100%", padding: icon ? "10px 12px 10px 32px" : "10px 12px",
              borderRadius: V.radiusSm, border: `1px solid ${sc.border}`,
              fontFamily: monospace ? "'JetBrains Mono', ui-monospace, Consolas, monospace" : V.font,
              fontSize: 13, color: isFilled ? V.brown : V.brownFaded,
              background: sc.bg, outline: "none", boxSizing: "border-box",
              fontWeight: monospace ? V.fw.sb : V.fw.r,
              letterSpacing: monospace ? "0.02em" : "normal",
              fontVariantNumeric: monospace ? "tabular-nums" : "normal",
              transition: "border-color 0.2s, background 0.2s",
            }}
            onFocus={e => e.target.style.borderColor = V.orange}
            onBlur={e => e.target.style.borderColor = sc.border}
          />
        )}
      </div>
      {note && (
        <div style={{
          display: "flex", alignItems: "center", gap: 5, marginTop: 5,
          fontSize: 11, color: status === "missing" ? V.danger : status === "low" ? V.warning : status === "corrected" || status === "spelled" ? V.purple : V.brownFaded,
        }}>
          <Icon name={status === "missing" ? "alert" : status === "low" ? "alert" : status === "corrected" ? "refresh" : status === "spelled" ? "wand" : "info"} size={11} color="currentColor"/>
          {note}
        </div>
      )}
      {error && (
        <div style={{ marginTop: 5, fontSize: 11, color: V.danger, display: "flex", alignItems: "center", gap: 5 }}>
          <Icon name="alert" size={11} color={V.danger}/> {error}
        </div>
      )}
    </div>
  );
};

// Section header with eyebrow + count
const SectionHeader = ({ eyebrow, title, subtitle, count, total, right }) => (
  <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", marginBottom: 18 }}>
    <div>
      {eyebrow && <Eyebrow style={{ marginBottom: 6 }}>{eyebrow}</Eyebrow>}
      <div style={{
        fontFamily: V.font, fontSize: 20, fontWeight: V.fw.m, color: V.brown, lineHeight: 1.1,
        letterSpacing: "-0.01em",
      }}>{title}</div>
      {subtitle && <div style={{ marginTop: 4, fontSize: 12, color: V.brownMid, fontFamily: V.font }}>{subtitle}</div>}
    </div>
    {(count !== undefined || right) && (
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        {count !== undefined && (
          <div style={{
            fontFamily: V.font, fontSize: 11, color: V.brownMid,
            fontVariantNumeric: "tabular-nums",
          }}>
            <span style={{ fontWeight: V.fw.sb, color: V.brown }}>{count}</span>
            <span style={{ color: V.brownFaded }}> / {total}</span> filled
          </div>
        )}
        {right}
      </div>
    )}
  </div>
);

const Card = ({ children, style, pad = 28 }) => (
  <div style={{
    background: V.white, border: `1px solid ${V.borderMed}`, borderRadius: V.radius,
    padding: pad, ...style,
  }}>{children}</div>
);

// Step indicator chip for header
const StepChip = ({ num, label, state }) => {
  // state: "done" | "active" | "pending"
  const cfg = {
    done:    { bg: V.successBg,   fg: V.success, border: "transparent" },
    active:  { bg: V.orangeLight, fg: V.orange,  border: V.orange },
    pending: { bg: "transparent", fg: V.brownFaded, border: V.borderMed },
  }[state];
  return (
    <div style={{
      display: "inline-flex", alignItems: "center", gap: 8,
      padding: "5px 11px 5px 6px", borderRadius: V.radiusPill,
      background: cfg.bg, border: `1px solid ${cfg.border}`,
      fontFamily: V.font, fontSize: 12, fontWeight: V.fw.m, color: cfg.fg,
    }}>
      <span style={{
        width: 18, height: 18, borderRadius: "50%",
        background: state === "done" ? V.success : state === "active" ? V.orange : "rgba(36,20,13,.06)",
        color: state === "pending" ? V.brownMid : V.white,
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        fontSize: 10, fontWeight: V.fw.sb,
      }}>
        {state === "done" ? <Icon name="check" size={10} color={V.white}/> : num}
      </span>
      {label}
    </div>
  );
};

// Minimal audio player widget — visual-only play/pause + duration display.
const MiniPlayer = ({ duration }) => {
  const [playing, setPlaying] = React.useState(false);
  const fmt = (s) => {
    if (!s && s !== 0) return "--:--";
    return `${String(Math.floor(s / 60)).padStart(2, "0")}:${String(Math.floor(s % 60)).padStart(2, "0")}`;
  };
  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
      <button
        onClick={() => setPlaying(p => !p)}
        style={{
          width: 28, height: 28, borderRadius: "50%",
          background: V.orange, border: "none", cursor: "pointer",
          display: "flex", alignItems: "center", justifyContent: "center",
          boxShadow: V.shadowOrange, flexShrink: 0,
        }}
      >
        <Icon name={playing ? "pause" : "play"} size={12} color={V.white}/>
      </button>
      <span style={{ fontFamily: V.font, fontSize: 11, color: V.brownMid, fontVariantNumeric: "tabular-nums" }}>
        {fmt(duration)}
      </span>
    </div>
  );
};

Object.assign(window, { V, Icon, Button, Eyebrow, FocusCorners, ConfidenceBadge, StatusPill, FormField, SectionHeader, Card, StepChip, MiniPlayer });
