/* global React */
const { useState } = React;

// ===================== SETTINGS =====================
function SettingsScreen({
  tweaks,
  setTweaks,
  models = window.MODELS,
  model,
  setModel,
  thinkingLevels = window.THINKING_LEVELS || [],
  thinkingLevel,
  setThinkingLevel,
  systemPrompt,
  setSystemPrompt,
  temperature,
  setTemperature,
  onClearConversations,
  onExportConversations,
  conversationCount,
}) {
  const [tab, setTab] = useState("api");

  return (
    <div className="screen settings">
      <div className="screen-inner">
        <h1 className="screen-title">Settings</h1>
        <p className="screen-sub">Manage models, assistant behavior, and conversation data.</p>

        <div className="settings-layout">
          <nav className="settings-nav">
            {[
              ["api", "API & models"],
              ["prompt", "System prompt"],
              ["appearance", "Appearance"],
              ["data", "Data & privacy"],
            ].map(([k, label]) => (
              <button key={k} className={"settings-nav-btn " + (tab === k ? "active" : "")} onClick={() => setTab(k)}>
                {label}
              </button>
            ))}
          </nav>

          <div className="settings-pane">
            {tab === "api" && (
              <>
                <Field label="Vertex AI service account" hint="Cloudflare Worker uses encrypted secrets; the browser never sees the private key.">
                  <div className="plan-row">
                    <span className="plan-pill big">Worker secrets</span>
                    <span className="field-hint mono">GOOGLE_CLIENT_EMAIL / GOOGLE_PRIVATE_KEY</span>
                  </div>
                </Field>
                <Field label="Default model">
                  <div className="radio-row">
                    {models.map(m => (
                      <label key={m.id} className="radio-card">
                        <input type="radio" name="model" checked={m.id === model} onChange={() => setModel(m.id)} />
                        <span className="model-glyph">{m.glyph}</span>
                        <span className="radio-card-text">
                          <span className="radio-card-label">{m.label}</span>
                          <span className="radio-card-sub">{m.sub}</span>
                        </span>
                      </label>
                    ))}
                  </div>
                </Field>
                <Field label="Thinking level" hint="Controls Gemini 3 internal reasoning. Auto leaves the decision to the model; Minimal is coerced to Low on Pro if unsupported.">
                  <div className="radio-row thinking-row">
                    {thinkingLevels.map(l => (
                      <label key={l.id} className="radio-card">
                        <input type="radio" name="thinkingLevel" checked={l.id === thinkingLevel} onChange={() => setThinkingLevel(l.id)} />
                        <span className="radio-card-text">
                          <span className="radio-card-label">{l.label}</span>
                          <span className="radio-card-sub">{l.sub}</span>
                        </span>
                      </label>
                    ))}
                  </div>
                </Field>
                <Field label="Temperature" hint="How exploratory replies feel. Lower = more precise.">
                  <input type="range" min="0" max="1" step="0.05" value={temperature} onChange={(e) => setTemperature(e.target.value)} className="slider" />
                  <div className="field-hint mono">{Number(temperature).toFixed(2)}</div>
                </Field>
              </>
            )}

            {tab === "prompt" && (
              <Field label="System prompt" hint="Sent with every conversation. Keep it short and concrete.">
                <textarea className="text-input mono" rows={8} value={systemPrompt} onChange={(e) => setSystemPrompt(e.target.value)} />
              </Field>
            )}

            {tab === "appearance" && (
              <>
                <Field label="Theme">
                  <div className="seg">
                    <button className={"seg-btn " + (!tweaks.dark ? "on" : "")} onClick={() => setTweaks("dark", false)}>Light</button>
                    <button className={"seg-btn " + (tweaks.dark ? "on" : "")} onClick={() => setTweaks("dark", true)}>Dark</button>
                  </div>
                </Field>
                <Field label="Accent">
                  <div className="swatch-row">
                    {Object.entries({ terracotta: "Terracotta", forest: "Forest", ink: "Ink", ochre: "Ochre" }).map(([k, name]) => (
                      <button key={k} className={"swatch " + (tweaks.accent === k ? "on" : "")} onClick={() => setTweaks("accent", k)} data-accent={k}>
                        <span className="swatch-dot" />
                        <span>{name}</span>
                      </button>
                    ))}
                  </div>
                </Field>
                <Field label="Density">
                  <div className="seg">
                    <button className={"seg-btn " + (tweaks.density === "comfy" ? "on" : "")} onClick={() => setTweaks("density", "comfy")}>Comfy</button>
                    <button className={"seg-btn " + (tweaks.density === "compact" ? "on" : "")} onClick={() => setTweaks("density", "compact")}>Compact</button>
                  </div>
                </Field>
              </>
            )}

            {tab === "data" && (
              <>
                <Field label="Conversation history" hint={`${conversationCount} conversation${conversationCount === 1 ? "" : "s"} stored in D1 for this browser identity.`}>
                  <button className="ghost-btn danger" disabled={conversationCount === 0} onClick={onClearConversations}>Delete all conversations</button>
                </Field>
                <Field label="Export" hint="Download a .json archive of every conversation.">
                  <button className="ghost-btn" disabled={conversationCount === 0} onClick={onExportConversations}>Export archive</button>
                </Field>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

function Field({ label, hint, children }) {
  return (
    <div className="field">
      <div className="field-head">
        <label className="field-label">{label}</label>
        {hint && <span className="field-hint">{hint}</span>}
      </div>
      <div className="field-control">{children}</div>
    </div>
  );
}

// ===================== HISTORY =====================
function HistoryScreen({ convos, onOpen }) {
  const [q, setQ] = useState("");
  const filtered = q ? convos.filter(c => c.title.toLowerCase().includes(q.toLowerCase()) || c.preview.toLowerCase().includes(q.toLowerCase())) : convos;
  const groups = {};
  for (const c of filtered) (groups[c.date] = groups[c.date] || []).push(c);

  return (
    <div className="screen history">
      <div className="screen-inner">
        <h1 className="screen-title">All history</h1>
        <p className="screen-sub">{convos.length} conversations.</p>
        <div className="history-search">
          <svg viewBox="0 0 24 24" width="14" height="14"><circle cx="11" cy="11" r="6" fill="none" stroke="currentColor" strokeWidth="1.5"/><path d="m20 20-3.5-3.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
          <input placeholder="Search every conversation" value={q} onChange={(e) => setQ(e.target.value)} />
        </div>
        {filtered.length === 0 && (
          <div className="side-empty">{q ? "No matching conversations." : "No conversations yet."}</div>
        )}
        {Object.entries(groups).map(([date, list]) => (
          <section className="hist-group" key={date}>
            <h3 className="hist-date">{date}</h3>
            <div className="hist-list">
              {list.map(c => (
                <button key={c.id} className="hist-item" onClick={() => onOpen(c.id)}>
                  <span className="hist-title">{c.title}</span>
                  <span className="hist-preview">{c.preview}</span>
                </button>
              ))}
            </div>
          </section>
        ))}
      </div>
    </div>
  );
}

// ===================== SHORTCUTS OVERLAY =====================
function ShortcutsOverlay({ onClose }) {
  const groups = [
    ["General", [
      ["⌘", "K", "New conversation"],
      ["⌘", "/", "Toggle sidebar"],
      ["?", "", "Show this overlay"],
      ["Esc", "", "Dismiss dialogs"],
    ]],
    ["In a conversation", [
      ["↵", "", "Send message"],
      ["⇧", "↵", "New line"],
      ["⌘", "↑", "Edit last message"],
    ]],
    ["Navigation", [
      ["⌘", "1–9", "Jump to recent chat"],
      ["⌘", ".", "Open settings"],
      ["⌘", "H", "All history"],
    ]],
  ];
  return (
    <div className="overlay" onClick={onClose}>
      <div className="shortcuts" onClick={(e) => e.stopPropagation()}>
        <div className="shortcuts-head">
          <h3>Keyboard shortcuts</h3>
          <button className="icon-btn" onClick={onClose} aria-label="Close">
            <svg viewBox="0 0 24 24" width="16" height="16"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
          </button>
        </div>
        <div className="shortcuts-grid">
          {groups.map(([title, list]) => (
            <div className="shortcut-group" key={title}>
              <h4>{title}</h4>
              {list.map(([a, b, label], i) => (
                <div key={i} className="shortcut-row">
                  <span>{label}</span>
                  <span className="kbds">
                    <kbd>{a}</kbd>
                    {b && <kbd>{b}</kbd>}
                  </span>
                </div>
              ))}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

window.SettingsScreen = SettingsScreen;
window.HistoryScreen = HistoryScreen;
window.ShortcutsOverlay = ShortcutsOverlay;
