// Settings — a second panel sliding in, with left subnav and right form.

const { useState: uS_s } = React;

function SettingsView({ density }) {
  const [section, setSection] = uS_s("general");
  const sections = [
    { id: "general", label: "General" },
    { id: "transcription", label: "Transcription" },
    { id: "hotkeys", label: "Hotkeys" },
    { id: "audio", label: "Audio" },
    { id: "notch", label: "Notch overlay" },
    { id: "privacy", label: "Privacy & data" },
    { id: "account", label: "Account" },
    { id: "developer", label: "Developer" },
  ];

  return (
    <div style={{ display: "flex", height: "100%", overflow: "hidden" }}>
      <nav
        style={{
          width: 180,
          padding: "24px 12px",
          borderRight: "1px solid var(--line-soft)",
          display: "flex",
          flexDirection: "column",
          gap: 1,
        }}
      >
        <div
          style={{
            fontSize: 11,
            color: "var(--ink-mute)",
            textTransform: "uppercase",
            letterSpacing: "0.06em",
            padding: "0 10px 8px",
          }}
        >
          Settings
        </div>
        {sections.map((s) => {
          const active = section === s.id;
          return (
            <button
              key={s.id}
              onClick={() => setSection(s.id)}
              style={{
                textAlign: "left",
                padding: "7px 10px",
                borderRadius: 7,
                border: "none",
                background: active ? "rgba(2,2,2,.06)" : "transparent",
                color: active ? "var(--ink)" : "var(--ink-soft)",
                fontSize: 12.5,
                fontWeight: active ? 500 : 400,
                cursor: "pointer",
                transition: "background 120ms ease",
              }}
              onMouseEnter={(e) => {
                if (!active) e.currentTarget.style.background = "rgba(2,2,2,.03)";
              }}
              onMouseLeave={(e) => {
                if (!active) e.currentTarget.style.background = "transparent";
              }}
            >
              {s.label}
            </button>
          );
        })}
      </nav>

      <div style={{ flex: 1, overflowY: "auto" }}>
        <PageShell
          title={sections.find((s) => s.id === section)?.label}
          density={density}
        >
          {section === "general" && <GeneralSettings />}
          {section === "transcription" && <TranscriptionSettings />}
          {section === "hotkeys" && <HotkeySettings />}
          {section === "audio" && <AudioSettings />}
          {section === "notch" && <NotchSettings />}
          {section === "privacy" && <PrivacySettings />}
          {section === "account" && <AccountSettings />}
          {section === "developer" && <DeveloperSettings />}
        </PageShell>
      </div>
    </div>
  );
}

function SettingsGroup({ title, children }) {
  return (
    <div style={{ marginBottom: 24 }}>
      {title && (
        <div
          style={{
            fontSize: 11,
            color: "var(--ink-mute)",
            textTransform: "uppercase",
            letterSpacing: "0.06em",
            marginBottom: 10,
          }}
        >
          {title}
        </div>
      )}
      <div
        style={{
          background: "#fff",
          borderRadius: 14,
          overflow: "hidden",
        }}
      >
        {children}
      </div>
    </div>
  );
}

function SettingsRow({ label, hint, control }) {
  return (
    <div
      style={{
        padding: "12px 16px",
        display: "flex",
        alignItems: "center",
        gap: 16,
        borderBottom: "1px solid var(--line-soft)",
      }}
    >
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 500 }}>{label}</div>
        {hint && <div style={{ fontSize: 12, color: "var(--ink-mute)", marginTop: 2 }}>{hint}</div>}
      </div>
      {control}
    </div>
  );
}

function GeneralSettings() {
  const [launch, setLaunch] = uS_s(true);
  const [menubar, setMenubar] = uS_s(true);
  const [dock, setDock] = uS_s(false);
  const [appLang, setAppLang] = uS_s("English");
  const [dictLang, setDictLang] = uS_s("Auto detect");
  return (
    <>
      <SettingsGroup title="App">
        <SettingsRow label="Launch at login" control={<Toggle on={launch} onChange={setLaunch} />} />
        <SettingsRow label="Show in menu bar" control={<Toggle on={menubar} onChange={setMenubar} />} />
        <SettingsRow
          label="Show in Dock"
          hint="Hiding the dock icon keeps globefn out of ⌘-Tab."
          control={<Toggle on={dock} onChange={setDock} />}
        />
        <SettingsRow
          label="App language"
          hint="Language for the globefn interface"
          control={
            <InputShell style={{ width: 160, height: 28 }}>
              <span style={{ flex: 1 }}>{appLang}</span>
              <Ic.chevDown width="12" height="12" />
            </InputShell>
          }
        />
        <SettingsRow
          label="Dictation language"
          hint="Language globefn listens for when you speak"
          control={
            <InputShell style={{ width: 160, height: 28 }}>
              <span style={{ flex: 1 }}>{dictLang}</span>
              <Ic.chevDown width="12" height="12" />
            </InputShell>
          }
        />
      </SettingsGroup>
    </>
  );
}

function TranscriptionSettings() {
  const [streaming, setStreaming] = uS_s(true);
  const [punct, setPunct] = uS_s(true);
  const [vad, setVad] = uS_s(true);
  return (
    <SettingsGroup title="Transcription">
      <SettingsRow label="Streaming transcription" hint="Show words as you speak" control={<Toggle on={streaming} onChange={setStreaming} />} />
      <SettingsRow label="Auto-punctuation" control={<Toggle on={punct} onChange={setPunct} />} />
      <SettingsRow label="Trim leading silence" control={<Toggle on={vad} onChange={setVad} />} />
    </SettingsGroup>
  );
}

function HotkeySettings() {
  return (
    <SettingsGroup title="Hotkeys">
      <SettingsRow
        label="Dictate"
        hint="Hold to start, release to send"
        control={
          <div style={{ display: "flex", gap: 4 }}>
            <Keycap label="alt" width={32} height={32} soft />
          </div>
        }
      />
      <SettingsRow
        label="Correction"
        hint="Rewrite and fix selected text"
        control={
          <div style={{ display: "flex", gap: 4 }}>
            <Keycap label="⌘" width={32} height={32} soft />
            <Keycap label="⇧" width={32} height={32} soft />
            <Keycap label="C" width={32} height={32} soft />
          </div>
        }
      />
      <SettingsRow
        label="Agent mode"
        hint="Trigger the agent on your current context"
        control={
          <div style={{ display: "flex", gap: 4 }}>
            <Keycap label="⌘" width={32} height={32} soft />
            <Keycap label="⇧" width={32} height={32} soft />
            <Keycap label="A" width={32} height={32} soft />
          </div>
        }
      />
    </SettingsGroup>
  );
}

function AudioSettings() {
  const [mic, setMic] = uS_s("MacBook Pro Mic");
  const [monitor, setMonitor] = uS_s(false);
  return (
    <SettingsGroup title="Audio">
      <SettingsRow
        label="Input"
        control={
          <InputShell style={{ width: 200, height: 28 }}>
            <span style={{ flex: 1 }}>{mic}</span>
            <Ic.chevDown width="12" height="12" />
          </InputShell>
        }
      />
      <SettingsRow label="Monitor input" hint="Hear your mic while dictating" control={<Toggle on={monitor} onChange={setMonitor} />} />
    </SettingsGroup>
  );
}

function NotchSettings() {
  const [show, setShow] = uS_s(true);
  return (
    <SettingsGroup title="Notch overlay">
      <SettingsRow label="Show overlay while dictating" control={<Toggle on={show} onChange={setShow} />} />
    </SettingsGroup>
  );
}

function PrivacySettings() {
  const [retain, setRetain] = uS_s(true);
  const [telemetry, setTelemetry] = uS_s(false);
  return (
    <SettingsGroup title="Privacy">
      <SettingsRow label="Keep transcription history" hint="Stored locally. Never sent to servers." control={<Toggle on={retain} onChange={setRetain} />} />
      <SettingsRow label="Share anonymous usage" control={<Toggle on={telemetry} onChange={setTelemetry} />} />
      <SettingsRow label="Delete all history" hint="Permanent, cannot be undone" control={<Pill>Clear</Pill>} />
    </SettingsGroup>
  );
}

function AccountSettings() {
  const currentPlan = "pro";
  const [billingCycle, setBillingCycle] = uS_s("annual");

  const plans = [
    {
      id: "free",
      name: "Free",
      price: "$0",
      period: "forever",
      features: [
        "2,000 transcribed words per week",
        "20 agent interactions per week",
      ],
    },
    {
      id: "pro",
      name: "Pro",
      monthlyPrice: "€15",
      annualPrice: "€12",
      annualTotal: "€144",
      period: "/mo",
      includes: "All Free features +",
      features: [
        "Everything unlimited",
        "Dedicated support",
      ],
    },
  ];

  return (
    <>
      <SettingsGroup title="Account">
        <SettingsRow label="Email" control={<span style={{ fontSize: 12.5, color: "var(--ink-mute)" }}>lea@globefn.com</span>} />
        <SettingsRow label="Current plan" hint="12,480 words used this week" control={<span style={{ fontSize: 12.5, fontWeight: 500 }}>Pro · Annual</span>} />
      </SettingsGroup>

      <div style={{ marginBottom: 24 }}>
        <div style={{ display: "flex", alignItems: "center", marginBottom: 10 }}>
          <div style={{ fontSize: 11, color: "var(--ink-mute)", textTransform: "uppercase", letterSpacing: "0.06em", flex: 1 }}>Plans</div>
          <div style={{ display: "inline-flex", background: "#f2f2f2", borderRadius: 999, padding: 2 }}>
            {[
              { id: "monthly", label: "Monthly" },
              { id: "annual", label: "Annual · save 20%" },
            ].map((o) => {
              const active = billingCycle === o.id;
              return (
                <button key={o.id} onClick={() => setBillingCycle(o.id)}
                  style={{ padding: "5px 12px", borderRadius: 999, border: "none", cursor: "pointer", fontSize: 11.5, fontWeight: active ? 500 : 400, background: active ? "#fff" : "transparent", color: active ? "var(--ink)" : "var(--ink-soft)", boxShadow: active ? "0 1px 2px rgba(0,0,0,0.06)" : "none", transition: "all 120ms ease" }}>
                  {o.label}
                </button>
              );
            })}
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 10 }}>
          {plans.map((p) => {
            const isCurrent = p.id === currentPlan;
            const price = p.price
              ? p.price
              : billingCycle === "monthly"
              ? p.monthlyPrice
              : p.annualPrice;
            const period = p.period || "";
            return (
              <div key={p.id}
                style={{
                  position: "relative",
                  border: isCurrent ? "1.5px solid var(--ink)" : "1.5px solid transparent",
                  borderRadius: 18,
                  background: "var(--card-bg)",
                  padding: 16,
                  display: "flex",
                  flexDirection: "column",
                  gap: 12,
                }}>
                {p.badge && (
                  <span style={{ position: "absolute", top: -8, right: 12, fontSize: 10, fontWeight: 500, padding: "2px 8px", borderRadius: 999, background: "var(--ink)", color: "#fff", letterSpacing: "0.02em" }}>
                    {p.badge}
                  </span>
                )}

                <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
                  <span style={{ fontSize: 14, fontWeight: 600 }}>{p.name}</span>
                  {isCurrent && (
                    <span style={{ fontSize: 10.5, color: "var(--ink-mute)", border: "0.5px solid var(--line)", borderRadius: 999, padding: "1px 7px" }}>Current</span>
                  )}
                </div>

                <div style={{ display: "flex", alignItems: "baseline", gap: 4 }}>
                  <span style={{ fontSize: 26, fontWeight: 600, letterSpacing: "-0.01em" }}>{price}</span>
                  {period && <span style={{ fontSize: 12, color: "var(--ink-mute)" }}>{period}</span>}
                  {!p.price && p.annualTotal && billingCycle === "annual" && (
                    <span style={{ fontSize: 11, color: "var(--ink-mute)", marginLeft: 4 }}>· {p.annualTotal} billed yearly</span>
                  )}
                </div>
                {p.subtitle && (
                  <div style={{ fontSize: 11.5, color: "var(--ink-mute)", marginTop: -6 }}>{p.subtitle}</div>
                )}

                {p.includes && (
                  <div style={{ fontSize: 11.5, color: "var(--ink-mute)" }}>{p.includes}</div>
                )}

                <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 6 }}>
                  {p.features.map((f, i) => (
                    <li key={i} style={{ display: "flex", alignItems: "flex-start", gap: 8, fontSize: 12.5, color: "var(--ink)" }}>
                      <svg width="12" height="12" viewBox="0 0 12 12" fill="none" style={{ flexShrink: 0, marginTop: 3 }}>
                        <path d="M2.5 6.5L5 9L9.5 3.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
                      </svg>
                      <span>{f}</span>
                    </li>
                  ))}
                </ul>

                <div style={{ flex: 1 }} />

                <button
                  disabled={isCurrent}
                  style={{
                    marginTop: 2,
                    padding: "9px 12px",
                    fontSize: 12.5,
                    fontWeight: 500,
                    borderRadius: 8,
                    cursor: isCurrent ? "default" : "pointer",
                    border: isCurrent ? "1px solid var(--line)" : "1px solid var(--ink)",
                    background: isCurrent ? "transparent" : p.id === "enterprise" ? "#fff" : "var(--ink)",
                    color: isCurrent ? "var(--ink-mute)" : p.id === "enterprise" ? "var(--ink)" : "#fff",
                    transition: "all 120ms ease",
                  }}>
                  {isCurrent
                    ? "Current plan"
                    : p.id === "enterprise"
                    ? "Contact sales"
                    : p.id === "free"
                    ? "Downgrade"
                    : "Upgrade"}
                </button>
              </div>
            );
          })}
        </div>
      </div>

      <SettingsGroup title="Billing">
        <SettingsRow label="Payment method" hint="Visa ending in 4242" control={<Pill>Update</Pill>} />
        <SettingsRow label="Next billing" control={<span style={{ fontSize: 12.5, color: "var(--ink-mute)" }}>May 17, 2026 · €144</span>} />
        <SettingsRow label="Invoices" control={<Pill>View</Pill>} />
      </SettingsGroup>
    </>
  );
}

function DeveloperSettings() {
  return (
    <SettingsGroup title="Developer">
      <SettingsRow label="API access" hint="Programmatic access via CLI or MCP" control={<Pill>Open</Pill>} />
      <SettingsRow label="Show debug logs" control={<Toggle on={false} onChange={() => {}} />} />
    </SettingsGroup>
  );
}

window.SettingsView = SettingsView;
