// Floating Copilot Window — Screen 1
// Strict adherence to DESIGN.md tokens. Six zones, top to bottom.

const DEFAULT_QUESTION =
  "¿Cómo separarías nuestra red por VLANs si tenemos invitados, servidores y VoIP?";

const DEFAULT_ANSWER =
  "Separaría usuarios, invitados, servidores, VoIP e IoT en VLANs distintas, y controlaría el tráfico entre ellas desde el firewall.";

const DEFAULT_NOTES = [
  { key: "VLAN 10",  text: "Usuarios internos — acceso completo a recursos corporativos" },
  { key: "VLAN 20",  text: "Guest aislada — sólo internet, sin tráfico hacia LAN" },
  { key: "VLAN 30",  text: "Servidores — acceso restringido por reglas explícitas" },
  { key: "VLAN 40",  text: "VoIP con QoS y DSCP marcado en el switch" },
  { key: "Inter-VLAN", text: "Reglas en firewall L3 — deny by default + allow específico" },
  { key: "Switch",   text: "Switches gestionables L2/L3 con soporte 802.1Q" },
];

const ACTIONS = [
  { id: "rephrase", label: "Reformular",    Icon: IconRefresh },
  { id: "shorter",  label: "Más corto",     Icon: IconShorter },
  { id: "tech",     label: "Más técnico",   Icon: IconCpu },
  { id: "comm",     label: "Más comercial", Icon: IconBriefcase },
  { id: "honest",   label: "No inventar",   Icon: IconAlert },
  { id: "context",  label: "Pedir contexto",Icon: IconHelp },
];

// Variants triggered by Zone 5 buttons — demonstrates real interactivity.
const VARIANTS = {
  default: {
    answer: DEFAULT_ANSWER,
    notes: DEFAULT_NOTES,
    confidence: "high",
  },
  rephrase: {
    answer:
      "Pondría cada tipo de tráfico en su propia VLAN — usuarios, invitados, servidores, VoIP e IoT — y dejaría que el firewall decida qué puede hablar con qué.",
    notes: DEFAULT_NOTES,
    confidence: "high",
  },
  shorter: {
    answer:
      "Una VLAN por cada tipo de tráfico, y el firewall en medio.",
    notes: [
      { key: "VLAN", text: "Una por tipo de usuario" },
      { key: "FW",   text: "Reglas inter-VLAN explícitas" },
      { key: "QoS",  text: "Prioridad para VoIP" },
    ],
    confidence: "high",
  },
  tech: {
    answer:
      "Segmentaría con VLANs 802.1Q por dominio de tráfico, trunk 802.1Q entre switch y firewall, e inter-VLAN routing en el firewall L3 con políticas deny-by-default.",
    notes: [
      { key: "802.1Q",     text: "Tagging en trunks switch ↔ firewall" },
      { key: "DHCP relay", text: "ip helper-address por VLAN al servidor central" },
      { key: "Private VLAN", text: "Aislamiento intra-VLAN para guest" },
      { key: "DSCP EF",    text: "Marcado VoIP en el access port" },
      { key: "STP",        text: "RSTP + BPDU guard en bordes" },
      { key: "ACLs",       text: "Inter-VLAN en firewall, no en switch L3" },
    ],
    confidence: "high",
  },
  comm: {
    answer:
      "Lo que hacemos es separar cada tipo de tráfico en su propia red lógica para que el invitado nunca vea los servidores, y la voz tenga prioridad. Es un estándar en empresas serias.",
    notes: [
      { key: "Beneficio", text: "Invitados nunca ven datos internos" },
      { key: "Beneficio", text: "Llamadas sin cortes ni eco" },
      { key: "Cumple",    text: "Buenas prácticas ISO 27001 / ENS" },
      { key: "Tiempo",    text: "Implementable en 2–3 jornadas" },
    ],
    confidence: "medium",
  },
  honest: {
    answer:
      "El diseño base son 5 VLANs separadas con firewall en medio. Para detalles concretos de tu infraestructura — modelos de switch, número de sedes, VPN — necesito ver tu inventario antes de comprometerme con números.",
    notes: [
      { key: "Sé",     text: "VLANs por tipo de tráfico — estándar" },
      { key: "Sé",     text: "Inter-VLAN routing en firewall L3" },
      { key: "No sé",  text: "Modelos exactos de switch que tienes" },
      { key: "No sé",  text: "Si hay ya un firewall L3 capaz" },
      { key: "Pedir",  text: "Inventario hardware + diagrama actual" },
    ],
    confidence: "medium",
  },
  context: {
    answer:
      "Antes de proponer un diseño concreto, ¿me puedes confirmar tres cosas: cuántos usuarios y dispositivos tienes hoy, qué firewall y switches, y si hay requisito de cumplir algún marco como ENS o PCI?",
    notes: [
      { key: "Q1", text: "¿Número aproximado de usuarios e IoT?" },
      { key: "Q2", text: "¿Marca y modelo de firewall y switches?" },
      { key: "Q3", text: "¿Hay un requisito de compliance específico?" },
      { key: "Q4", text: "¿Una sede o varias? ¿VPN site-to-site?" },
    ],
    confidence: "low",
  },
};

const CONFIDENCE_LABEL = {
  high: "Confianza: Alta",
  medium: "Confianza: Media",
  low: "Confianza: Baja",
};
const CONFIDENCE_VAR = {
  high:   { bg: "var(--accent-success-muted)", fg: "var(--accent-success)" },
  medium: { bg: "var(--accent-warning-muted)", fg: "var(--accent-warning)" },
  low:    { bg: "var(--accent-danger-muted)",  fg: "var(--accent-danger)"  },
};

// Compute opacity tier per DESIGN.md §10.1
function opacityTier(value) {
  if (value >= 90) return "full";
  if (value >= 75) return "medium";
  return "low";
}

function formatTime(seconds) {
  const m = Math.floor(seconds / 60);
  const s = seconds % 60;
  return `${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
}

const FloatingCopilot = ({ position }) => {
  // ---- State
  const [elapsed, setElapsed] = React.useState(12 * 60 + 34);
  const [clientOn, setClientOn] = React.useState(true);
  const [micOn, setMicOn] = React.useState(true);
  const [opacity, setOpacity] = React.useState(95);
  const [showOpacity, setShowOpacity] = React.useState(false);
  const [provider, setProvider] = React.useState("cloud");
  const [activeAction, setActiveAction] = React.useState("default");
  const [question, setQuestion] = React.useState(DEFAULT_QUESTION);
  const [questionDirty, setQuestionDirty] = React.useState(false);
  const [copied, setCopied] = React.useState(false);
  const [speaking, setSpeaking] = React.useState(false);
  const [toasts, setToasts] = React.useState([]);

  // tick clock
  React.useEffect(() => {
    const id = setInterval(() => setElapsed((s) => s + 1), 1000);
    return () => clearInterval(id);
  }, []);

  const variant = VARIANTS[activeAction] || VARIANTS.default;
  const tier = opacityTier(opacity);
  const conf = CONFIDENCE_VAR[variant.confidence];

  // ---- Toasts
  const pushToast = (toast) => {
    const id = Math.random().toString(36).slice(2);
    setToasts((t) => [...t, { id, ...toast }]);
    setTimeout(() => {
      setToasts((t) => t.filter((x) => x.id !== id));
    }, 2400);
  };

  // ---- Handlers
  const handleCopy = () => {
    if (navigator.clipboard) {
      navigator.clipboard.writeText(variant.answer).catch(() => {});
    }
    setCopied(true);
    pushToast({
      variant: "success",
      message: "Respuesta copiada al portapapeles",
    });
    setTimeout(() => setCopied(false), 1600);
  };

  const handleSpeak = () => {
    setSpeaking(true);
    pushToast({ variant: "info", message: "Leyendo en voz baja por TTS…" });
    setTimeout(() => setSpeaking(false), 1800);
  };

  const handleAction = (id) => {
    setActiveAction((cur) => (cur === id ? "default" : id));
  };

  const handleClear = () => {
    setActiveAction("default");
    setQuestion(DEFAULT_QUESTION);
    setQuestionDirty(false);
    pushToast({ variant: "info", message: "Sesión limpia. Esperando pregunta…" });
  };

  const handleReanalyze = () => {
    setQuestionDirty(false);
    setActiveAction("default");
    pushToast({ variant: "info", message: "Reanalizando con la pregunta editada…" });
  };

  // ---- Window opacity → background CSS
  // We translate opacity to alpha on bg.elevated (#1E1E23) per §10.1.
  const opacityAlpha = Math.max(0.6, opacity / 100);
  const bgStyle = {
    background:
      tier === "full"
        ? "var(--bg-elevated)"
        : `rgba(30, 30, 35, ${opacityAlpha})`,
    backdropFilter: tier === "full" ? "none" : "blur(20px) saturate(140%)",
    WebkitBackdropFilter: tier === "full" ? "none" : "blur(20px) saturate(140%)",
  };

  return (
    <>
      <div className="copilot-shell" style={position}>
        <div
          className="copilot-window"
          data-opacity-tier={tier}
          style={bgStyle}
        >
          {/* ============ ZONE 1 — HEADER ============ */}
          <div className="zone-header">
            <div className="rec-group">
              <div className="rec-dot" />
              <div className="rec-label">Grabando</div>
              <div className="rec-time">{formatTime(elapsed)}</div>
            </div>

            <div className="header-center">
              <button
                className="toggle-pill"
                data-on={clientOn}
                onClick={() => setClientOn((v) => !v)}
                title="Audio del cliente"
              >
                <span className="pill-dot" />
                Cliente: {clientOn ? "ON" : "OFF"}
              </button>
              <button
                className="toggle-pill"
                data-on={micOn}
                onClick={() => setMicOn((v) => !v)}
                title="Tu micrófono"
              >
                <span className="pill-dot" />
                Mic: {micOn ? "ON" : "OFF"}
              </button>
            </div>

            <div className="header-right">
              <button
                className={`icon-btn ${showOpacity ? "active" : ""}`}
                onClick={() => setShowOpacity((v) => !v)}
                title="Transparencia"
              >
                <IconSliders size={14} />
              </button>
              <button className="icon-btn" title="Configuración">
                <IconSettings size={14} />
              </button>
              <button className="icon-btn" title="Minimizar">
                <IconMinimize size={14} />
              </button>
            </div>
          </div>

          {/* ============ ZONE 2 — DETECTED QUESTION ============ */}
          <div className="zone-question">
            <div className="zone-label">
              <span>Pregunta del cliente</span>
              <span style={{
                fontFamily: "var(--font-mono)",
                color: "var(--fg-tertiary)",
                textTransform: "none",
                letterSpacing: 0
              }}>
                detectada hace 3s
              </span>
            </div>
            <div className={`q-textarea-wrap ${questionDirty ? "dirty" : ""}`}>
              <textarea
                className="q-textarea"
                value={question}
                onChange={(e) => {
                  setQuestion(e.target.value);
                  setQuestionDirty(e.target.value !== DEFAULT_QUESTION);
                }}
              />
              <button className="q-reanalyze" onClick={handleReanalyze}>
                <IconRefresh size={11} />
                Reanalizar
              </button>
            </div>
          </div>

          {/* ============ ZONE 3 — ANSWER ============ */}
          <div className="zone-answer">
            <div className="zone-answer-head">
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span className="zone-label" style={{ height: "auto" }}>
                  Para decir
                </span>
                <span
                  className="confidence-badge"
                  style={{
                    background: conf.bg,
                    color: conf.fg,
                  }}
                >
                  <span className="conf-dot" style={{ background: conf.fg }} />
                  {CONFIDENCE_LABEL[variant.confidence]}
                </span>
              </div>
              <div className="icons">
                <button
                  className="icon-btn"
                  onClick={handleCopy}
                  title="Copiar respuesta"
                  style={copied ? { color: "var(--accent-success)" } : {}}
                >
                  {copied ? <IconCheck size={14} /> : <IconCopy size={14} />}
                </button>
                <button
                  className="icon-btn"
                  onClick={handleSpeak}
                  title="Leer en voz alta (TTS)"
                  style={speaking ? { color: "var(--accent-primary)" } : {}}
                >
                  <IconVolume size={14} />
                </button>
              </div>
            </div>
            <div className="answer-text">{variant.answer}</div>
          </div>

          {/* ============ ZONE 4 — TECHNICAL NOTE ============ */}
          <div className="zone-note">
            <div className="note-head">
              <div className="note-label-group">
                <span className="zone-label" style={{ height: "auto" }}>
                  Apunte técnico
                </span>
                <span className="detail-badge">Detalle</span>
              </div>
              <span style={{
                fontSize: 11,
                color: "var(--fg-tertiary)",
                fontFamily: "var(--font-mono)"
              }}>
                {variant.notes.length} puntos
              </span>
            </div>
            <ul className="note-list">
              {variant.notes.map((n, i) => (
                <li className="note-item" key={i}>
                  <span className="note-bullet" />
                  <span className="note-key">{n.key}</span>
                  <span className="note-text">{n.text}</span>
                </li>
              ))}
            </ul>
          </div>

          {/* ============ ZONE 5 — ACTIONS ============ */}
          <div className="zone-actions">
            {ACTIONS.map(({ id, label, Icon: Ic }) => (
              <button
                key={id}
                className={`action-btn ${activeAction === id ? "engaged" : ""}`}
                onClick={() => handleAction(id)}
                title={label}
              >
                <Ic size={14} className="icon" />
                <span>{label}</span>
              </button>
            ))}
          </div>

          {/* ============ ZONE 6 — FOOTER ============ */}
          <div className="zone-footer">
            <div className="opacity-control">
              <span className="icon-eye"><IconEye size={14} /></span>
              <input
                className="opacity-slider"
                type="range"
                min={30}
                max={100}
                step={5}
                value={opacity}
                onChange={(e) => setOpacity(Number(e.target.value))}
              />
              <span className="opacity-value">{opacity}%</span>
            </div>

            <div className="segmented" role="tablist">
              {[
                { id: "local", label: "Local" },
                { id: "cloud", label: "Cloud" },
                { id: "byok",  label: "BYOK"  },
              ].map((p) => (
                <button
                  key={p.id}
                  className="seg-btn"
                  data-active={provider === p.id}
                  onClick={() => setProvider(p.id)}
                >
                  {p.label}
                </button>
              ))}
            </div>

            <button className="footer-clear" onClick={handleClear}>
              <IconTrash size={12} />
              Limpiar
            </button>
          </div>
        </div>
      </div>

      {/* Toasts */}
      <div className="toast-stack">
        {toasts.map((t) => (
          <div key={t.id} className={`toast ${t.variant || "info"}`}>
            <span className="toast-icon">
              {t.variant === "success" ? <IconCheck size={16} /> : <IconAlert size={16} />}
            </span>
            <span>{t.message}</span>
          </div>
        ))}
      </div>
    </>
  );
};

window.FloatingCopilot = FloatingCopilot;
