/* ─── Workspace Switcher (window-scoped) ─────────────────── */
const { useState: useStateWS, useEffect: useEffectWS, useRef: useRefWS } = React;

function WorkspaceAvatar({ ws, size = 30, square = true }) {
  return (
    <span
      style={{
        width: size, height: size,
        borderRadius: square ? 8 : "50%",
        background: ws.gradient || ws.color,
        color: "white",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        fontWeight: 800,
        fontSize: size > 28 ? 11 : 10,
        letterSpacing: "-0.02em",
        flexShrink: 0,
        boxShadow: "0 2px 6px rgba(15,30,50,0.15), inset 0 -1px 0 rgba(0,0,0,0.15)"
      }}
    >
      {ws.initials}
    </span>
  );
}

function WorkspaceSwitcher({ workspaces, activeId, onSwitch, onCreateNew }) {
  const [open, setOpen] = useStateWS(false);
  const ref = useRefWS(null);
  const active = workspaces.find(w => w.id === activeId) || workspaces[0];

  useEffectWS(() => {
    if (!open) return;
    const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    window.addEventListener("mousedown", handler);
    return () => window.removeEventListener("mousedown", handler);
  }, [open]);

  return (
    <div ref={ref} style={{ position: "relative", padding: "12px 12px 10px", borderBottom: "1px solid var(--line)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 8, paddingLeft: 2 }}>
        <Icon name="radar" size={10} color="var(--ink-3)" />
        <span style={{
          fontSize: 9.5, fontWeight: 700, color: "var(--ink-3)",
          textTransform: "uppercase", letterSpacing: "0.12em", fontFamily: "var(--font-mono)"
        }}>
          Discovery Radar
        </span>
      </div>

      <button
        type="button"
        onClick={() => setOpen(!open)}
        style={{
          display: "flex",
          alignItems: "center",
          gap: 10,
          width: "100%",
          padding: 7,
          background: open ? "var(--bg-2)" : "var(--bg-1)",
          border: `1px solid ${open ? "var(--brand)" : "var(--line-md)"}`,
          borderRadius: 9,
          cursor: "pointer",
          textAlign: "left",
          transition: "all 0.12s",
          boxShadow: open ? "0 0 0 3px var(--brand-dim)" : "none"
        }}
      >
        <WorkspaceAvatar ws={active} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink-0)", letterSpacing: "-0.01em", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
            {active.name}
          </div>
          <div style={{ fontSize: 10.5, color: "var(--ink-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", marginTop: 1 }}>
            {active.niche}
          </div>
        </div>
        <Icon name="chevron-down" size={13} color="var(--ink-3)" style={{ transform: open ? "rotate(180deg)" : "", transition: "transform 0.15s" }} />
      </button>

      {open && (
        <div
          style={{
            position: "absolute",
            top: "calc(100% - 2px)",
            left: 10,
            right: 10,
            background: "var(--bg-1)",
            border: "1px solid var(--line-md)",
            borderRadius: 12,
            boxShadow: "var(--sh-lg)",
            zIndex: 100,
            padding: 6,
            animation: "rdSlideUp 0.15s ease-out",
            maxHeight: 360,
            overflowY: "auto"
          }}
        >
          <div style={{
            fontSize: 9.5, fontWeight: 700, color: "var(--ink-3)",
            textTransform: "uppercase", letterSpacing: "0.12em", fontFamily: "var(--font-mono)",
            padding: "6px 8px 4px"
          }}>
            Workspaces ({workspaces.length})
          </div>
          {workspaces.map(ws => {
            const sel = ws.id === activeId;
            return (
              <button
                key={ws.id}
                type="button"
                onClick={() => { onSwitch(ws.id); setOpen(false); }}
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 10,
                  width: "100%",
                  padding: "7px 8px",
                  background: sel ? "var(--brand-dim)" : "transparent",
                  border: "none",
                  borderRadius: 7,
                  cursor: "pointer",
                  textAlign: "left",
                  marginBottom: 1
                }}
                onMouseEnter={(e) => { if (!sel) e.currentTarget.style.background = "var(--bg-2)"; }}
                onMouseLeave={(e) => { if (!sel) e.currentTarget.style.background = "transparent"; }}
              >
                <WorkspaceAvatar ws={ws} size={26} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12, fontWeight: 600, color: "var(--ink-0)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{ws.name}</div>
                  <div style={{ fontSize: 10.5, color: "var(--ink-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{ws.niche}</div>
                </div>
                {sel && <Icon name="check" size={13} color="var(--brand)" strokeWidth={2.5} />}
              </button>
            );
          })}
          <div style={{ height: 1, background: "var(--line)", margin: "6px 4px" }} />
          <button
            type="button"
            onClick={() => { setOpen(false); onCreateNew(); }}
            style={{
              display: "flex", alignItems: "center", gap: 9,
              width: "100%", padding: "8px 8px",
              background: "transparent", border: "none", borderRadius: 7,
              cursor: "pointer", textAlign: "left",
              color: "var(--brand)", fontWeight: 600, fontSize: 12
            }}
            onMouseEnter={(e) => e.currentTarget.style.background = "var(--brand-dim)"}
            onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
          >
            <span style={{ width: 26, height: 26, borderRadius: 8, background: "var(--brand-dim)", border: "1px dashed var(--brand)", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <Icon name="plus" size={13} color="var(--brand)" strokeWidth={2.4} />
            </span>
            Criar novo workspace
          </button>
        </div>
      )}
    </div>
  );
}

/* ─── New Workspace Modal ─────────────────────────────────────────────── */
const WS_PALETTE = [
  { color: "#1A56DB", gradient: "linear-gradient(135deg, #1A56DB 0%, #0B3FAE 100%)" },
  { color: "#7C3AED", gradient: "linear-gradient(135deg, #7C3AED 0%, #5B21B6 100%)" },
  { color: "#10B981", gradient: "linear-gradient(135deg, #10B981 0%, #047857 100%)" },
  { color: "#F59E0B", gradient: "linear-gradient(135deg, #F59E0B 0%, #B45309 100%)" },
  { color: "#EF4444", gradient: "linear-gradient(135deg, #EF4444 0%, #991B1B 100%)" },
  { color: "#0891B2", gradient: "linear-gradient(135deg, #0891B2 0%, #155E75 100%)" },
  { color: "#EC4899", gradient: "linear-gradient(135deg, #EC4899 0%, #9D174D 100%)" },
  { color: "#0F172A", gradient: "linear-gradient(135deg, #334155 0%, #0F172A 100%)" }
];

const NICHE_PRESETS = [
  { label: "Fintech B2B",         keywords: ["pagamentos", "open finance", "PIX", "PSP"]},
  { label: "Healthtech",          keywords: ["telemedicina", "saúde digital", "ANS"]},
  { label: "Foodtech",            keywords: ["delivery", "dark kitchen", "food service"]},
  { label: "Edtech / L&D",        keywords: ["LXP", "corporate learning", "skills"]},
  { label: "Logística",           keywords: ["last mile", "fulfillment", "logtech"]},
  { label: "Real Estate / Proptech",keywords: ["proptech", "mercado imobiliário", "iBuying"]},
  { label: "Agro",                keywords: ["agritech", "agro digital", "AgFin"]},
  { label: "Outro",               keywords: []}
];

function NewWorkspaceModal({ open, onClose, onCreate }) {
  const [step, setStep] = useStateWS(1);
  const [name, setName] = useStateWS("");
  const [niche, setNiche] = useStateWS("");
  const [description, setDescription] = useStateWS("");
  const [palette, setPalette] = useStateWS(WS_PALETTE[1]);
  const [preset, setPreset] = useStateWS("");

  useEffectWS(() => {
    if (open) {
      setStep(1); setName(""); setNiche(""); setDescription("");
      setPalette(WS_PALETTE[Math.floor(Math.random() * WS_PALETTE.length)]);
      setPreset("");
    }
  }, [open]);

  if (!open) return null;

  const initials = name.split(/\s+/).filter(Boolean).slice(0, 2).map(w => w[0]?.toUpperCase()).join("") || "??";
  const preview = { name: name || "Novo Workspace", niche: niche || "—", initials, color: palette.color, gradient: palette.gradient };

  const canCreate = name.trim().length >= 2 && niche.trim().length >= 2;

  const handleCreate = () => {
    onCreate({
      id: `ws-${Date.now()}`,
      name: name.trim(),
      niche: niche.trim(),
      description: description.trim(),
      color: palette.color,
      gradient: palette.gradient,
      initials,
      categoryOverrides: {},
      members: 1,
      plan: "Starter"
    });
    onClose();
  };

  const applyPreset = (p) => {
    setPreset(p.label);
    if (!niche) setNiche(p.label);
  };

  return (
    <div className="rd-modal-overlay" onClick={onClose}>
      <div className="rd-modal" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 600 }}>
        <div className="rd-modal-header">
          <div>
            <div className="rd-modal-title">
              <span style={{ width: 24, height: 24, borderRadius: 6, background: palette.gradient, display: "inline-flex", alignItems: "center", justifyContent: "center", color: "white" }}>
                <Icon name="plus" size={13} strokeWidth={2.4} />
              </span>
              Novo workspace
            </div>
            <div className="rd-modal-subtitle">
              Cada workspace é um nicho independente — com seus próprios triggers, insights e contexto de IA
            </div>
          </div>
          <button className="rd-modal-close" onClick={onClose}>
            <Icon name="x" size={14} />
          </button>
        </div>

        <div className="rd-modal-body">
          {/* Preview card */}
          <div className="rd-section" style={{ background: "var(--bg-2)" }}>
            <div style={{
              display: "flex", alignItems: "center", gap: 14,
              padding: 16, background: "var(--bg-1)",
              border: "1px solid var(--line)", borderRadius: 12
            }}>
              <WorkspaceAvatar ws={preview} size={48} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 15, fontWeight: 700, color: "var(--ink-0)" }}>{preview.name}</div>
                <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{preview.niche}</div>
              </div>
              <span className="rd-tag brand">PREVIEW</span>
            </div>
          </div>

          <div className="rd-section">
            <div className="rd-field">
              <label className="rd-label">Nome do workspace <span className="req">*</span></label>
              <input
                className="rd-input"
                placeholder="ex: Stark Pagamentos, Vita Saúde, Acme Foodtech"
                value={name}
                onChange={(e) => setName(e.target.value)}
                autoFocus
              />
              <div className="rd-hint">Geralmente o nome do produto ou da empresa.</div>
            </div>

            <div className="rd-field">
              <label className="rd-label">Nicho / Vertical <span className="req">*</span></label>
              <input
                className="rd-input"
                placeholder="ex: Fintech B2B · Pagamentos & Open Finance"
                value={niche}
                onChange={(e) => setNiche(e.target.value)}
              />
              <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginTop: 8 }}>
                {NICHE_PRESETS.map(p => (
                  <button
                    key={p.label}
                    type="button"
                    onClick={() => applyPreset(p)}
                    className={`rd-chip ${preset === p.label ? "" : "neutral"}`}
                    style={{ padding: "4px 10px", cursor: "pointer", fontSize: 11 }}
                  >
                    {p.label}
                  </button>
                ))}
              </div>
            </div>

            <div className="rd-field">
              <label className="rd-label">Descrição <span className="opt">(opcional)</span></label>
              <textarea
                className="rd-textarea"
                placeholder="O que esse radar monitora? Quem é o público? Esse texto vai como contexto para o agente de IA."
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                style={{ minHeight: 76 }}
              />
            </div>

            <div className="rd-field">
              <label className="rd-label">Cor & ícone</label>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                {WS_PALETTE.map((p, i) => {
                  const selected = palette.color === p.color;
                  return (
                    <button
                      key={i}
                      type="button"
                      onClick={() => setPalette(p)}
                      style={{
                        width: 40, height: 40, borderRadius: 10,
                        background: p.gradient, cursor: "pointer",
                        border: selected ? "2px solid var(--ink-0)" : "2px solid transparent",
                        boxShadow: selected ? "0 0 0 2px var(--bg-1), 0 0 0 4px var(--ink-0)" : "var(--sh-sm)",
                        display: "flex", alignItems: "center", justifyContent: "center",
                        color: "white", fontWeight: 800, fontSize: 12
                      }}
                    >
                      {selected && <Icon name="check" size={16} strokeWidth={3} color="white" />}
                    </button>
                  );
                })}
              </div>
            </div>
          </div>

          <div className="rd-section" style={{ background: "var(--bg-2)" }}>
            <div style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
              <Icon name="info" size={18} color="var(--brand)" style={{ flexShrink: 0, marginTop: 1 }} />
              <div style={{ fontSize: 12, color: "var(--ink-1)", lineHeight: 1.6 }}>
                Após criar o workspace, você poderá adicionar triggers com concorrentes, palavras-chave, fontes e APIs específicos do nicho. <strong>Dados não se misturam entre workspaces</strong> — cada um tem seu próprio feed, alertas e relatórios.
              </div>
            </div>
          </div>
        </div>

        <div className="rd-modal-footer">
          <div className="left">
            <span style={{ fontSize: 11.5, color: "var(--ink-3)" }}>
              Você poderá editar tudo isso depois em <strong>Configurações</strong>.
            </span>
          </div>
          <div className="right">
            <button type="button" className="rd-btn" onClick={onClose}>Cancelar</button>
            <button
              type="button"
              className="rd-btn primary"
              disabled={!canCreate}
              onClick={handleCreate}
            >
              <Icon name="sparkles" size={12} />
              Criar workspace
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { WorkspaceSwitcher, NewWorkspaceModal, WorkspaceAvatar });
