/* ─── Shared Components & Icons (window-scoped) ─────────────────── */
const { useState, useEffect, useRef, useMemo } = React;

/* ─── Icon ─────────────────────────────────────────────── */
function Icon({ name, size = 14, color = "currentColor", strokeWidth = 1.8, style }) {
  const props = {
    width: size, height: size, viewBox: "0 0 24 24",
    fill: "none", stroke: color, strokeWidth, strokeLinecap: "round", strokeLinejoin: "round", style
  };
  switch (name) {
    case "radar":     return <svg {...props}><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/><line x1="12" y1="2" x2="12" y2="6"/><line x1="2" y1="12" x2="6" y2="12"/></svg>;
    case "search":    return <svg {...props}><circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>;
    case "plus":      return <svg {...props}><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>;
    case "x":         return <svg {...props}><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>;
    case "check":     return <svg {...props}><polyline points="20 6 9 17 4 12"/></svg>;
    case "refresh":   return <svg {...props}><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"/></svg>;
    case "filter":    return <svg {...props}><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/></svg>;
    case "trending":  return <svg {...props}><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></svg>;
    case "swords":    return <svg {...props}><polyline points="14.5 17.5 3 6 3 3 6 3 17.5 14.5"/><line x1="13" y1="19" x2="19" y2="13"/><line x1="16" y1="16" x2="20" y2="20"/><line x1="19" y1="21" x2="21" y2="19"/><polyline points="14.5 6.5 18 3 21 3 21 6 17.5 9.5"/><line x1="5" y1="14" x2="9" y2="18"/><line x1="7" y1="17" x2="4" y2="20"/><line x1="3" y1="19" x2="5" y2="21"/></svg>;
    case "briefcase": return <svg {...props}><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 7V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2"/></svg>;
    case "calendar":  return <svg {...props}><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>;
    case "cpu":       return <svg {...props}><rect x="4" y="4" width="16" height="16" rx="2"/><rect x="9" y="9" width="6" height="6"/><line x1="9" y1="2" x2="9" y2="4"/><line x1="15" y1="2" x2="15" y2="4"/><line x1="9" y1="20" x2="9" y2="22"/><line x1="15" y1="20" x2="15" y2="22"/><line x1="20" y1="9" x2="22" y2="9"/><line x1="2" y1="9" x2="4" y2="9"/><line x1="20" y1="15" x2="22" y2="15"/><line x1="2" y1="15" x2="4" y2="15"/></svg>;
    case "gavel":     return <svg {...props}><path d="M14 13l-7.5 7.5a2.12 2.12 0 0 1-3-3L11 10"/><path d="M16 16l6-6"/><path d="M8 8l6-6"/><path d="M9 7l8 8"/><path d="M21 11l-8-8"/></svg>;
    case "bell":      return <svg {...props}><path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>;
    case "settings":  return <svg {...props}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>;
    case "play":      return <svg {...props}><polygon points="5 3 19 12 5 21 5 3"/></svg>;
    case "pause":     return <svg {...props}><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>;
    case "edit":      return <svg {...props}><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"/></svg>;
    case "trash":     return <svg {...props}><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>;
    case "copy":      return <svg {...props}><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>;
    case "external":  return <svg {...props}><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>;
    case "chevron":   return <svg {...props}><polyline points="9 18 15 12 9 6"/></svg>;
    case "chevron-down":return <svg {...props}><polyline points="6 9 12 15 18 9"/></svg>;
    case "bookmark":  return <svg {...props}><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></svg>;
    case "pin":       return <svg {...props}><line x1="12" y1="17" x2="12" y2="22"/><path d="M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24z"/></svg>;
    case "share":     return <svg {...props}><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>;
    case "arrow-up":  return <svg {...props}><line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/></svg>;
    case "arrow-down":return <svg {...props}><line x1="12" y1="5" x2="12" y2="19"/><polyline points="19 12 12 19 5 12"/></svg>;
    case "sparkles":  return <svg {...props}><path d="M12 3l1.9 5.7L20 11l-6.1 1.9L12 19l-1.9-6.1L4 11l6.1-1.9z"/><path d="M19 3v4M21 5h-4"/></svg>;
    case "globe":     return <svg {...props}><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>;
    case "tag":       return <svg {...props}><path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/></svg>;
    case "slack":     return <svg viewBox="0 0 24 24" width={size} height={size}><path fill="#E01E5A" d="M5 14.5A2 2 0 1 1 3 12.5h2zm1 0a2 2 0 1 1 4 0v5a2 2 0 1 1-4 0z"/><path fill="#36C5F0" d="M9.5 5a2 2 0 1 1 2-2v2zm0 1a2 2 0 1 1 0 4h-5a2 2 0 1 1 0-4z"/><path fill="#2EB67D" d="M19 9.5a2 2 0 1 1 2 2h-2zm-1 0a2 2 0 1 1-4 0v-5a2 2 0 1 1 4 0z"/><path fill="#ECB22E" d="M14.5 19a2 2 0 1 1-2 2v-2zm0-1a2 2 0 1 1 0-4h5a2 2 0 1 1 0 4z"/></svg>;
    case "mail":      return <svg {...props}><rect x="2" y="4" width="20" height="16" rx="2"/><polyline points="22,6 12,13 2,6"/></svg>;
    case "code":      return <svg {...props}><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>;
    case "clock":     return <svg {...props}><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>;
    case "zap":       return <svg {...props}><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>;
    case "list":      return <svg {...props}><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>;
    case "users":     return <svg {...props}><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>;
    case "alert":     return <svg {...props}><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>;
    case "info":      return <svg {...props}><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"/></svg>;
    case "menu":      return <svg {...props}><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="18" x2="21" y2="18"/></svg>;
    case "download":  return <svg {...props}><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"/></svg>;
    case "thumb-up":  return <svg {...props}><path d="M7 22V10M2 11h5v11H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2zM18 22h-7c-1.1 0-2-.9-2-2v-7c0-.7.2-1.4.6-2L14 5V2c1.7 0 3 1.3 3 3v5h4.5c1.4 0 2.4 1.3 2 2.6l-2.4 7.2c-.4 1.3-1.5 2.2-2.8 2.2z"/></svg>;
    case "thumb-down":return <svg {...props}><path d="M17 2v12M22 13h-5V2h3a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2zM6 2h7c1.1 0 2 .9 2 2v7c0 .7-.2 1.4-.6 2L10 19v3c-1.7 0-3-1.3-3-3v-5H2.5C1.1 14 .1 12.7.5 11.4l2.4-7.2C3.3 2.9 4.4 2 5.7 2H6z"/></svg>;
    case "brain":     return <svg {...props}><path d="M9.5 2A2.5 2.5 0 0 0 7 4.5v15A2.5 2.5 0 0 0 9.5 22a2.5 2.5 0 0 0 2.5-2.5V4.5A2.5 2.5 0 0 0 9.5 2zM14.5 2A2.5 2.5 0 0 1 17 4.5v15a2.5 2.5 0 0 1-2.5 2.5 2.5 2.5 0 0 1-2.5-2.5V4.5A2.5 2.5 0 0 1 14.5 2z"/><path d="M5 8H4a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h1M19 8h1a2 2 0 0 1 2 2v2a2 2 0 0 1-2 2h-1M5 14H4a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h1M19 14h1a2 2 0 0 1 2 2v2a2 2 0 0 1-2 2h-1"/></svg>;
    case "heart":     return <svg {...props}><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>;
    case "rocket":    return <svg {...props}><path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09zM12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"/><path d="M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"/></svg>;
    case "package":   return <svg {...props}><line x1="16.5" y1="9.4" x2="7.5" y2="4.21"/><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>;
    case "git-branch":return <svg {...props}><line x1="6" y1="3" x2="6" y2="15"/><circle cx="18" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><path d="M18 9a9 9 0 0 1-9 9"/></svg>;
    default: return null;
  }
}

/* ─── Radar logo glyph ─────────────────────────────────────────────── */
function RadarGlyph({ size = 16 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
      <circle cx="12" cy="12" r="10" stroke="white" strokeOpacity="0.4" strokeWidth="1.5"/>
      <circle cx="12" cy="12" r="6" stroke="white" strokeOpacity="0.6" strokeWidth="1.5"/>
      <circle cx="12" cy="12" r="2" fill="white"/>
      <path d="M12 12 L20 6" stroke="white" strokeWidth="2" strokeLinecap="round"/>
    </svg>
  );
}

/* ─── Toggle ─────────────────────────────────────────────── */
function Toggle({ on, onChange, size = "" }) {
  return (
    <button
      type="button"
      className={`rd-toggle${on ? " on" : ""}${size ? " " + size : ""}`}
      onClick={() => onChange(!on)}
      aria-pressed={on}
    />
  );
}

/* ─── Chip Input — used for Keywords / Competitors / Domains ─────────────────────── */
function ChipInput({ values, onChange, placeholder, variant = "" }) {
  const [draft, setDraft] = useState("");
  const inputRef = useRef(null);

  const add = (raw) => {
    const v = raw.trim().replace(/^,+|,+$/g, "").trim();
    if (!v) return;
    if (values.includes(v)) return;
    onChange([...values, v]);
    setDraft("");
  };
  const remove = (v) => onChange(values.filter(x => x !== v));

  const onKeyDown = (e) => {
    if (e.key === "Enter" || e.key === "," || e.key === "Tab") {
      if (draft.trim()) { e.preventDefault(); add(draft); }
    } else if (e.key === "Backspace" && !draft && values.length) {
      onChange(values.slice(0, -1));
    }
  };
  const onPaste = (e) => {
    const text = e.clipboardData.getData("text");
    if (text.includes(",") || text.includes("\n")) {
      e.preventDefault();
      text.split(/[,\n]/).forEach(t => add(t));
    }
  };

  return (
    <div className="rd-chip-input" onClick={() => inputRef.current?.focus()}>
      {values.map(v => (
        <span key={v} className={`rd-chip ${variant}`}>
          {v}
          <button type="button" onClick={(e) => { e.stopPropagation(); remove(v); }} aria-label={`Remover ${v}`}>
            <Icon name="x" size={11} />
          </button>
        </span>
      ))}
      <input
        ref={inputRef}
        value={draft}
        onChange={(e) => setDraft(e.target.value)}
        onKeyDown={onKeyDown}
        onPaste={onPaste}
        onBlur={() => draft.trim() && add(draft)}
        placeholder={values.length ? "" : placeholder}
      />
    </div>
  );
}

/* ─── Checkbox ─────────────────────────────────────────────── */
function Checkbox({ checked, onChange, label, count }) {
  return (
    <label className="rd-checkbox-row" onClick={(e) => e.stopPropagation()}>
      <span
        className={`rd-checkbox${checked ? " checked" : ""}`}
        onClick={() => onChange(!checked)}
      >
        {checked && <Icon name="check" size={11} strokeWidth={3} />}
      </span>
      <span style={{ flex: 1 }}>{label}</span>
      {count != null && <span className="count">{count}</span>}
    </label>
  );
}

/* ─── Segmented ─────────────────────────────────────────────── */
function Segmented({ value, onChange, options, wide }) {
  return (
    <div className={`rd-segmented${wide ? " wide" : ""}`}>
      {options.map(o => (
        <button
          key={o.value}
          type="button"
          className={value === o.value ? "active" : ""}
          onClick={() => onChange(o.value)}
        >
          {o.icon && <Icon name={o.icon} size={12} />}
          {o.label}
        </button>
      ))}
    </div>
  );
}

/* ─── Slider with value ─────────────────────────────────────────────── */
function Slider({ value, onChange, min = 0, max = 100, step = 1, unit = "%", labels }) {
  return (
    <div className="rd-slider-wrap">
      <div className="rd-slider-row">
        <input
          type="range"
          className="rd-slider"
          min={min} max={max} step={step}
          value={value}
          onChange={(e) => onChange(Number(e.target.value))}
        />
        <span className="rd-slider-val">{value}{unit}</span>
      </div>
      {labels && (
        <div style={{ display: "flex", justifyContent: "space-between", fontSize: 10.5, color: "var(--ink-3)", fontFamily: "var(--font-mono)", fontWeight: 600 }}>
          {labels.map((l, i) => <span key={i}>{l}</span>)}
        </div>
      )}
    </div>
  );
}

/* ─── Source initial avatar ─────────────────────────────────────────────── */
function SourceAvatar({ source, size = 26 }) {
  return (
    <span
      className="icon"
      style={{
        width: size, height: size,
        background: source.color,
        fontSize: size > 22 ? 11 : 9,
        borderRadius: 6
      }}
    >
      {source.initials}
    </span>
  );
}

/* ─── Toast ─────────────────────────────────────────────── */
function Toast({ message, onDone, icon = "check" }) {
  useEffect(() => {
    const t = setTimeout(onDone, 2600);
    return () => clearTimeout(t);
  }, [onDone]);
  return (
    <div className="rd-toast">
      <span className="icon"><Icon name={icon} size={16} strokeWidth={2.4} /></span>
      {message}
    </div>
  );
}

/* ─── Quick feedback buttons (train agent) ─────────────────────── */
function FeedbackButtons({ feedback, onChange, size = 26, persistent = false }) {
  return (
    <div className={`rd-fb-row${persistent ? " persistent" : ""}`} onClick={(e) => e.stopPropagation()}>
      <button
        type="button"
        title={feedback === "relevant" ? "Remover marcação" : "Marcar como relevante (treina o agente)"}
        className={`rd-fb-btn${feedback === "relevant" ? " on-up" : ""}`}
        style={{ width: size, height: size }}
        onClick={(e) => { e.stopPropagation(); onChange(feedback === "relevant" ? null : "relevant"); }}
      >
        <Icon name="thumb-up" size={13} strokeWidth={feedback === "relevant" ? 2.4 : 1.8} />
      </button>
      <button
        type="button"
        title={feedback === "irrelevant" ? "Remover marcação" : "Marcar como ruído (treina o agente)"}
        className={`rd-fb-btn${feedback === "irrelevant" ? " on-down" : ""}`}
        style={{ width: size, height: size }}
        onClick={(e) => { e.stopPropagation(); onChange(feedback === "irrelevant" ? null : "irrelevant"); }}
      >
        <Icon name="thumb-down" size={13} strokeWidth={feedback === "irrelevant" ? 2.4 : 1.8} />
      </button>
    </div>
  );
}

Object.assign(window, {
  Icon, RadarGlyph, Toggle, ChipInput, Checkbox, Segmented, Slider, SourceAvatar, Toast, FeedbackButtons
});
