// Settings — IA y API keys

const Ic = ({ size = 16, stroke = 1.75, children }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
       stroke="currentColor" strokeWidth={stroke}
       strokeLinecap="round" strokeLinejoin="round">{children}</svg>
);
const IcLogoSm   = (p) => <Ic {...p} stroke={2}><path d="M12 2v4"/><path d="M12 18v4"/><path d="M4.93 4.93l2.83 2.83"/><path d="M16.24 16.24l2.83 2.83"/><path d="M2 12h4"/><path d="M18 12h4"/><path d="M4.93 19.07l2.83-2.83"/><path d="M16.24 7.76l2.83-2.83"/></Ic>;
const IcSettings = (p) => <Ic {...p}><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-2.83 2.83l-.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 1 1-2.83-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 1 1 2.83-2.83l.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 1 1 2.83 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"/></Ic>;
const IcVolume   = (p) => <Ic {...p}><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"/></Ic>;
const IcCpu      = (p) => <Ic {...p}><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="20" y1="14" x2="22" y2="14"/><line x1="2" y1="9" x2="4" y2="9"/><line x1="2" y1="14" x2="4" y2="14"/></Ic>;
const IcLayers   = (p) => <Ic {...p}><polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></Ic>;
const IcKeyboard = (p) => <Ic {...p}><rect x="2" y="6" width="20" height="12" rx="2"/><line x1="6" y1="10" x2="6" y2="10"/><line x1="10" y1="10" x2="10" y2="10"/><line x1="14" y1="10" x2="14" y2="10"/><line x1="18" y1="10" x2="18" y2="10"/><line x1="7" y1="14" x2="17" y2="14"/></Ic>;
const IcPalette  = (p) => <Ic {...p}><circle cx="13.5" cy="6.5" r="1" fill="currentColor"/><circle cx="17.5" cy="10.5" r="1" fill="currentColor"/><circle cx="8.5" cy="7.5" r="1" fill="currentColor"/><circle cx="6.5" cy="12.5" r="1" fill="currentColor"/><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.83 0 1.5-.67 1.5-1.5 0-.39-.15-.74-.39-1.01-.23-.26-.38-.61-.38-.99 0-.83.67-1.5 1.5-1.5H16c3.31 0 6-2.69 6-6 0-4.96-4.49-9-10-9z"/></Ic>;
const IcUser2   = (p) => <Ic {...p}><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></Ic>;
const IcShield   = (p) => <Ic {...p}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></Ic>;
const IcInfo     = (p) => <Ic {...p}><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"/></Ic>;
const IcChev     = (p) => <Ic {...p} stroke={2}><polyline points="6 9 12 15 18 9"/></Ic>;
const IcSearch   = (p) => <Ic {...p}><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></Ic>;
const IcEye      = (p) => <Ic {...p}><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"/></Ic>;
const IcEyeOff   = (p) => <Ic {...p}><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></Ic>;
const IcExt      = (p) => <Ic {...p}><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"/></Ic>;
const IcCheck    = (p) => <Ic {...p} stroke={2}><polyline points="20 6 9 17 4 12"/></Ic>;
const IcAlert    = (p) => <Ic {...p}><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"/></Ic>;

const TABS = [
  { id: "general",   icon: IcSettings, label: "General" },
  { id: "audio",     icon: IcVolume,   label: "Audio" },
  { id: "ai",        icon: IcCpu,      label: "IA y API keys" },
  { id: "templates", icon: IcLayers,   label: "Plantillas" },
  { id: "shortcuts", icon: IcKeyboard, label: "Atajos de teclado" },
  { id: "appearance",icon: IcPalette,  label: "Apariencia" },
  { id: "account",   icon: IcUser2,    label: "Cuenta y plan" },
  { id: "privacy",   icon: IcShield,   label: "Privacidad" },
  { id: "about",     icon: IcInfo,     label: "Acerca de" },
];

const PROVIDERS = [
  { id: "anthropic", name: "Anthropic Claude", desc: "Recomendado para respuestas técnicas precisas" },
  { id: "openai",    name: "OpenAI GPT",       desc: "Alternativa rápida y versátil" },
];

const MODELS_BY_PROVIDER = {
  anthropic: [
    "Claude Haiku 4.5 (Más rápido y barato)",
    "Claude Sonnet 4.5 (Equilibrio rendimiento/coste)",
    "Claude Opus 4.1 (Máxima calidad)",
  ],
  openai: [
    "GPT-4o mini (Rápido y barato)",
    "GPT-4o (Equilibrado)",
    "GPT-4 Turbo (Máxima calidad)",
  ],
};

const ApiKeyCard = ({ provider, label, helpUrl, helpText }) => {
  const [show, setShow] = React.useState(false);
  const [val, setVal]   = React.useState("");
  const isValid = val.length >= 12;
  return (
    <div className="ai-keycard">
      <div className="ai-keycard-head">
        <div className="ai-keycard-title">
          <span className="ai-keycard-prov">{provider}</span>
          <span className="ai-keycard-name">{label}</span>
        </div>
        <span className={`ai-status ${isValid ? "ok" : "neutral"}`}>
          {isValid ? <><IcCheck size={11} /> Válida</> : "No configurada"}
        </span>
      </div>
      <div className="ai-keycard-input">
        <input type={show ? "text" : "password"}
               placeholder="sk-..." value={val}
               onChange={(e) => setVal(e.target.value)} />
        <button className="ai-eye" onClick={() => setShow((v) => !v)}
                title={show ? "Ocultar" : "Mostrar"}>
          {show ? <IcEyeOff size={13} /> : <IcEye size={13} />}
        </button>
      </div>
      <a className="ai-link" href="#" onClick={(e) => e.preventDefault()}>
        {helpText} <IcExt size={10} />
      </a>
    </div>
  );
};

const SettingsAI = () => {
  const [tab, setTab]            = React.useState("ai");
  const [mode, setMode]          = React.useState("cloud"); // local | cloud | byok
  const [provider, setProvider]  = React.useState("anthropic");
  const [model, setModel]        = React.useState(MODELS_BY_PROVIDER.anthropic[0]);
  const [modelOpen, setModelOpen] = React.useState(false);

  const onProvider = (id) => {
    setProvider(id);
    setModel(MODELS_BY_PROVIDER[id][0]);
  };

  const ollamaOk = true;

  return (
    <div className="stg-root" data-screen-label="09 Settings IA y API Keys">
      <header className="dash-header">
        <div className="dash-brand">
          <div className="dash-mark"><IcLogoSm size={14} /></div>
          <span className="dash-brand-name">Copilotoprompter</span>
          <span className="bcrumb">/ Configuración</span>
        </div>
        <div className="dash-h-spacer" />
        <div className="avatar">JM</div>
      </header>

      <div className="stg-body">
        <aside className="stg-side">
          <div className="stg-search">
            <IcSearch size={13} />
            <input placeholder="Buscar ajustes…" />
          </div>
          <nav className="stg-nav">
            {TABS.map(({ id, icon: Icon, label }) => (
              <button key={id}
                      className={`stg-tab ${tab === id ? "active" : ""}`}
                      onClick={() => setTab(id)}>
                <Icon size={14} />
                <span>{label}</span>
              </button>
            ))}
          </nav>
        </aside>

        <main className="stg-main">
          <div className="stg-content ai-content">
            <div className="stg-page-head">
              <h1>IA y API keys</h1>
              <p>Configura cómo quieres usar los modelos de IA.</p>
            </div>

            {/* Sección 1 — Motor */}
            <section className="ai-section">
              <header className="ai-sec-head">
                <h2>Motor de IA activo</h2>
                <p>Elige dónde se ejecuta el modelo que genera las sugerencias.</p>
              </header>
              <div className="ai-segmented">
                {[
                  { id: "local", label: "Local",  hint: "Privado, sin red" },
                  { id: "cloud", label: "Cloud",  hint: "Recomendado" },
                  { id: "byok",  label: "BYOK",   hint: "Tus claves" },
                ].map((s) => (
                  <button key={s.id}
                          className={`ai-seg ${mode === s.id ? "active" : ""}`}
                          onClick={() => setMode(s.id)}>
                    <span className="ai-seg-label">{s.label}</span>
                    <span className="ai-seg-hint">{s.hint}</span>
                  </button>
                ))}
              </div>
            </section>

            {/* Sección 2 — Cloud config */}
            {mode === "cloud" && (
              <section className="ai-section">
                <header className="ai-sec-head">
                  <h2>Configuración Cloud</h2>
                  <p>Selecciona proveedor y modelo. Las llamadas se realizan desde el servidor de Copilotoprompter.</p>
                </header>

                <div className="ai-field">
                  <label className="ai-label">Proveedor cloud</label>
                  <div className="ai-radio-cards">
                    {PROVIDERS.map((p) => (
                      <button key={p.id}
                              className={`ai-radio-card ${provider === p.id ? "selected" : ""}`}
                              onClick={() => onProvider(p.id)}>
                        <span className={`ai-radio-dot ${provider === p.id ? "on" : ""}`}>
                          <span />
                        </span>
                        <span className="ai-radio-text">
                          <span className="ai-radio-name">{p.name}</span>
                          <span className="ai-radio-desc">{p.desc}</span>
                        </span>
                        {provider === p.id && (
                          <span className="ai-radio-badge">Activo</span>
                        )}
                      </button>
                    ))}
                  </div>
                </div>

                <div className="ai-field">
                  <label className="ai-label">Modelo</label>
                  <div className="stg-dd ai-model-dd">
                    <button className="stg-dd-btn ai-model-btn" onClick={() => setModelOpen((v) => !v)}>
                      <span>{model}</span>
                      <IcChev size={12} />
                    </button>
                    {modelOpen && (
                      <div className="stg-dd-menu" onMouseLeave={() => setModelOpen(false)}>
                        {MODELS_BY_PROVIDER[provider].map((m) => (
                          <button key={m}
                                  className={`stg-dd-item ${model === m ? "selected" : ""}`}
                                  onClick={() => { setModel(m); setModelOpen(false); }}>
                            <span>{m}</span>
                            {model === m && <span className="stg-dd-check">✓</span>}
                          </button>
                        ))}
                      </div>
                    )}
                  </div>
                  <p className="ai-hint">
                    Coste estimado: <b>~0,05 €</b> por reunión de 1 hora.
                  </p>
                </div>
              </section>
            )}

            {/* Sección 3 — BYOK */}
            <section className="ai-section">
              <header className="ai-sec-head">
                <h2>
                  Tus API keys
                  <span className="ai-badge-opt">Opcional</span>
                </h2>
                <p>Usa tus propias claves para facturar el consumo directamente con el proveedor.</p>
              </header>
              <div className="ai-keycards">
                <ApiKeyCard
                  provider="Anthropic"
                  label="Anthropic API Key"
                  helpText="Obtener API key en console.anthropic.com" />
                <ApiKeyCard
                  provider="OpenAI"
                  label="OpenAI API Key"
                  helpText="Obtener API key en platform.openai.com" />
              </div>
            </section>

            {/* Sección 4 — Ollama */}
            <section className="ai-section">
              <header className="ai-sec-head">
                <h2>Ollama (IA local)</h2>
                <p>Ejecuta los modelos directamente en tu equipo, sin enviar datos a la nube.</p>
              </header>
              <div className="ai-ollama">
                <div className={`ai-ollama-status ${ollamaOk ? "ok" : "err"}`}>
                  {ollamaOk
                    ? <><IcCheck size={13} /><span>Detectado · <code>qwen2.5:7b</code> instalado</span></>
                    : <><IcAlert size={13} /><span>No detectado en este equipo</span></>}
                </div>
                <div className="ai-ollama-actions">
                  <button className="btn-secondary stg-btn-sm">Configurar Ollama</button>
                  <a className="ai-link" href="#" onClick={(e) => e.preventDefault()}>
                    Instalar Ollama <IcExt size={10} />
                  </a>
                </div>
              </div>
            </section>
          </div>
        </main>
      </div>
    </div>
  );
};

window.SettingsAI = SettingsAI;
