// Shared icons + atoms. Exposes globals at bottom.
const { useState, useEffect, useRef, useMemo, useLayoutEffect } = React;

// Stroke-only icons, 20px viewBox; size via prop.
const Icon = ({ d, size = 18, stroke = 1.5, fill = "none", style }) => (
  <svg width={size} height={size} viewBox="0 0 20 20" fill={fill} stroke="currentColor" strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round" style={style}>
    {Array.isArray(d) ? d.map((p, i) => <path key={i} d={p} />) : <path d={d} />}
  </svg>
);

const Icons = {
  dashboard: (p) => <Icon {...p} d={["M3 3h6v8H3z", "M11 3h6v5h-6z", "M11 10h6v7h-6z", "M3 13h6v4H3z"]} />,
  leads:     (p) => <Icon {...p} d={["M4 7a3 3 0 116 0 3 3 0 01-6 0z", "M2 17c0-2.5 2-4.5 5-4.5s5 2 5 4.5", "M13 9.5a2.2 2.2 0 100-4.4", "M18 16c0-1.8-1.4-3.3-3.5-3.6"]} />,
  campaign:  (p) => <Icon {...p} d={["M3 8v4l11 4V4z", "M3 8H2.5A1.5 1.5 0 001 9.5v1A1.5 1.5 0 002.5 12H3", "M6 12v3.5a1.5 1.5 0 003 0V13"]} />,
  reports:   (p) => <Icon {...p} d={["M3 17V8", "M8 17V4", "M13 17v-7", "M18 17v-4", "M2 17h17"]} />,
  settings:  (p) => <Icon {...p} d={["M10 7a3 3 0 100 6 3 3 0 000-6z", "M16.2 12.3l1.4.7-1.4 2.4-1.5-.4a6 6 0 01-1.5.9l-.3 1.6h-2.8l-.3-1.6a6 6 0 01-1.5-.9l-1.5.4-1.4-2.4 1.4-.7a6 6 0 010-1.7L3.4 9.6l1.4-2.4 1.5.4a6 6 0 011.5-.9L8.1 5h2.8l.3 1.6a6 6 0 011.5.9l1.5-.4 1.4 2.4-1.4.7a6 6 0 010 1.7z"]} />,
  search:    (p) => <Icon {...p} d={["M9 3a6 6 0 110 12A6 6 0 019 3z", "M14 14l4 4"]} />,
  bell:      (p) => <Icon {...p} d={["M5 8a5 5 0 0110 0v3l1.5 3h-13L5 11z", "M8 17a2 2 0 004 0"]} />,
  chevDown:  (p) => <Icon {...p} d="M5 8l5 5 5-5" />,
  chevRight: (p) => <Icon {...p} d="M8 5l5 5-5 5" />,
  trendUp:   (p) => <Icon {...p} d={["M3 13l5-5 3 3 6-6", "M13 5h4v4"]} />,
  list:      (p) => <Icon {...p} d={["M3 5h14", "M3 10h14", "M3 15h14"]} />,
  kanban:    (p) => <Icon {...p} d={["M3 3h4v14H3z", "M8.5 3h3v10h-3z", "M13 3h4v8h-4z"]} />,
  filter:    (p) => <Icon {...p} d="M3 4h14l-5 7v5l-4-2v-3z" />,
  sort:      (p) => <Icon {...p} d={["M5 4v12", "M3 6l2-2 2 2", "M15 16V4", "M13 14l2 2 2-2"]} />,
  dots:      (p) => <Icon {...p} d={["M5 10h0.01", "M10 10h0.01", "M15 10h0.01"]} stroke={3} />,
  pin:       (p) => <Icon {...p} d={["M8 2l4 4-1.5 1.5L13 10l-3 3-2.5-2.5L6 12H4v-2l1.5-1.5L3 6l3-3z"]} />,
  check:     (p) => <Icon {...p} d="M4 10l4 4 8-9" />,
  x:         (p) => <Icon {...p} d={["M5 5l10 10", "M15 5L5 15"]} />,
  phone:     (p) => <Icon {...p} d="M4 4h3l1.5 4-2 1.5a10 10 0 005 5L13 12.5l4 1.5v3a2 2 0 01-2 2A12 12 0 014 6a2 2 0 010-2z" />,
  mail:      (p) => <Icon {...p} d={["M2 5h16v10H2z", "M2 6l8 5 8-5"]} />,
  pencil:    (p) => <Icon {...p} d={["M3 17l4-1 9-9-3-3-9 9z", "M12 4l3 3"]} />,
  arrow:     (p) => <Icon {...p} d={["M4 10h12", "M12 6l4 4-4 4"]} />,
  plus:      (p) => <Icon {...p} d={["M10 4v12", "M4 10h12"]} />,
  calendar:  (p) => <Icon {...p} d={["M3 5h14v12H3z", "M3 8h14", "M7 3v4", "M13 3v4"]} />,
};

// Avatar with initials; deterministic color by agent or hash fallback.
function Avatar({ initials, color = "#5684CC", size = 28, ring = false }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: 999,
      background: color + "22",
      color: color,
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      fontWeight: 600, fontSize: Math.round(size * 0.38),
      letterSpacing: 0.2, flexShrink: 0,
      border: ring ? `2px solid ${color}` : "none",
      lineHeight: 1,
    }}>{initials}</div>
  );
}

// Inline-editable text. Click to edit; Enter / blur to commit; Esc to cancel.
function EditableText({ value, onChange, style, multiline = false, prefix = "", suffix = "", className = "", placeholder = "" }) {
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState(value);
  const ref = useRef(null);
  useEffect(() => { if (!editing) setDraft(value); }, [value, editing]);
  useEffect(() => {
    if (editing && ref.current) { ref.current.focus(); ref.current.select?.(); }
  }, [editing]);

  const commit = () => { onChange?.(draft); setEditing(false); };
  const cancel = () => { setDraft(value); setEditing(false); };

  if (editing) {
    const Tag = multiline ? "textarea" : "input";
    return (
      <Tag
        ref={ref}
        value={draft}
        onChange={(e) => setDraft(e.target.value)}
        onBlur={commit}
        onKeyDown={(e) => {
          if (e.key === "Enter" && !multiline) { e.preventDefault(); commit(); }
          if (e.key === "Escape") cancel();
        }}
        style={{
          ...style,
          background: "#FFFEF7",
          border: "1px solid #A3E494",
          outline: "none",
          borderRadius: 4,
          padding: "1px 4px",
          margin: "-2px -5px",
          font: "inherit",
          color: "inherit",
          minWidth: 30,
          ...(multiline ? { resize: "vertical", width: "100%" } : {}),
        }}
      />
    );
  }
  return (
    <span
      className={className}
      onClick={(e) => { e.stopPropagation(); setEditing(true); }}
      style={{ ...style, cursor: "text", borderRadius: 3, padding: "1px 2px", margin: "-1px -2px" }}
      title="Click to edit"
    >{prefix}{value || <span style={{color: "#bbb"}}>{placeholder}</span>}{suffix}</span>
  );
}

// Status chip / stage badge with click-to-change.
function StageBadge({ stageId, stages, onChange, interactive = true, compact = false }) {
  const stage = stages.find(s => s.id === stageId) || stages[0];
  const [open, setOpen] = useState(false);
  const wrapRef = useRef(null);
  useEffect(() => {
    if (!open) return;
    const close = (e) => { if (!wrapRef.current?.contains(e.target)) setOpen(false); };
    window.addEventListener("mousedown", close);
    return () => window.removeEventListener("mousedown", close);
  }, [open]);
  return (
    <span ref={wrapRef} style={{ position: "relative", display: "inline-block" }}>
      <span
        onClick={(e) => { if (!interactive) return; e.stopPropagation(); setOpen(o => !o); }}
        style={{
          display: "inline-flex", alignItems: "center", gap: 6,
          padding: compact ? "2px 8px" : "4px 10px",
          borderRadius: 999,
          background: stage.bg,
          color: stage.fg,
          fontSize: compact ? 11 : 12,
          fontWeight: 500,
          lineHeight: 1.2,
          whiteSpace: "nowrap",
          cursor: interactive ? "pointer" : "default",
          border: "1px solid " + stage.fg + "1f",
        }}
      >
        <span style={{ width: 6, height: 6, borderRadius: 999, background: stage.color }} />
        {stage.label}
      </span>
      {open && (
        <div onClick={(e) => e.stopPropagation()} style={{
          position: "absolute", top: "calc(100% + 6px)", left: 0, zIndex: 80,
          background: "#fff", border: "1px solid #ECECEC", borderRadius: 10,
          padding: 6, minWidth: 200,
          boxShadow: "0 8px 24px rgba(15,20,35,0.08)",
        }}>
          {stages.map(s => (
            <div key={s.id}
              onClick={() => { onChange?.(s.id); setOpen(false); }}
              style={{
                display: "flex", alignItems: "center", gap: 8,
                padding: "7px 8px", borderRadius: 6, cursor: "pointer",
                fontSize: 12, color: "#1F2433",
                background: s.id === stageId ? "#F6FAF1" : "transparent",
              }}
              onMouseEnter={(e) => e.currentTarget.style.background = "#F6FAF1"}
              onMouseLeave={(e) => e.currentTarget.style.background = s.id === stageId ? "#F6FAF1" : "transparent"}
            >
              <span style={{ width: 8, height: 8, borderRadius: 999, background: s.color }} />
              {s.label}
            </div>
          ))}
        </div>
      )}
    </span>
  );
}

Object.assign(window, { Icon, Icons, Avatar, EditableText, StageBadge });
