// API Key screen — machine key management and local admin password change.
(function () {
  const NS = window.ChicoryTVDesignSystem_eb3b61;
  const { Button, IconButton, Card, Input, Spinner } = NS;
  const Ico = window.Ico;
  const mono = { fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" };

  // Mock data
  const MACHINE_KEY = "etv_0b4f8c2a1e9d5f3b7a6c4e2d0f1a8b9c5d3e2f1a0b4c6d8e9f0a1b2c3d4e5f6g";
  const mockAuthMethod = "local"; // 'local' or 'oidc' — determines if password card shows

  function CardFrame({ title, subtitle, children }) {
    return (
      <div style={{
        backgroundColor: "var(--surface-card)",
        border: "1px solid var(--border-hairline)",
        borderRadius: "var(--radius-md)",
        padding: "var(--pad-card)",
        display: "flex",
        flexDirection: "column",
        gap: 12
      }}>
        {title && (
          <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            <h2 style={{ margin: 0, font: "var(--weight-semibold) var(--text-md)/1.3 var(--font-sans)", color: "var(--text-primary)" }}>{title}</h2>
            {subtitle && (
              <p style={{ margin: 0, font: "var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-secondary)" }}>{subtitle}</p>
            )}
          </div>
        )}
        {children}
      </div>
    );
  }

  function MachineKeyCard() {
    const [revealed, setRevealed] = React.useState(false);
    const [copied, setCopied] = React.useState(false);

    const copy = () => {
      navigator.clipboard?.writeText(MACHINE_KEY).then(() => {
        setCopied(true);
        setTimeout(() => setCopied(false), 1500);
      });
    };

    return (
      <CardFrame
        title="Machine API Key"
        subtitle="This key authenticates MCP and external REST clients. The browser no longer uses it — you sign in with your account instead."
      >
        {/* Success callout */}
        <div style={{
          display: "flex",
          alignItems: "flex-start",
          gap: 10,
          padding: "12px 14px",
          borderRadius: "var(--radius-md)",
          backgroundColor: "var(--ctv-ok-soft)",
          border: "1px solid var(--status-ok)",
          color: "var(--text-primary)"
        }}>
          <Ico n="ShieldCheck" s={15} color="var(--status-ok)" style={{ flexShrink: 0, marginTop: 2 }} />
          <span style={{ font: "var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-primary)" }}>
            Give this key to an MCP server or external REST client to let it call this server's API.
          </span>
        </div>

        {/* Machine key field */}
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          <label style={{ font: "var(--weight-medium) var(--text-xs)/1 var(--font-sans)", letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--text-secondary)" }}>
            Machine key
          </label>
          <div style={{
            display: "flex",
            alignItems: "center",
            gap: 10,
            padding: "10px 12px",
            borderRadius: "var(--radius-md)",
            backgroundColor: "var(--ctv-bg-sunken)",
            border: "1px solid var(--border-control)",
            fontFamily: "var(--font-mono)"
          }}>
            <Ico n="KeyRound" s={14} color="var(--text-disabled)" />
            <code style={{
              flex: 1,
              overflowX: "auto",
              whiteSpace: "nowrap",
              font: "var(--text-sm)/1.3 var(--font-mono)",
              color: "var(--text-primary)",
              margin: 0,
              background: "none"
            }}>
              {revealed ? MACHINE_KEY : "••••••••••••••••••••••••"}
            </code>
          </div>
        </div>

        {/* Action buttons */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "flex-end", gap: 8, marginTop: 4 }}>
          <Button
            size="sm"
            variant="ghost"
            startIcon={revealed ? <Ico n="EyeOff" s={14} /> : <Ico n="Eye" s={14} />}
            onClick={() => setRevealed(!revealed)}
          >
            {revealed ? "Hide" : "Reveal"}
          </Button>
          <Button
            size="sm"
            variant="secondary"
            startIcon={copied ? <Ico n="Check" s={14} /> : <Ico n="Copy" s={14} />}
            onClick={copy}
          >
            {copied ? "Copied" : "Copy"}
          </Button>
        </div>
      </CardFrame>
    );
  }

  function LocalPasswordCard() {
    const [currentPassword, setCurrentPassword] = React.useState("");
    const [newPassword, setNewPassword] = React.useState("");
    const [saving, setSaving] = React.useState(false);
    const [error, setError] = React.useState(null);
    const [justSaved, setJustSaved] = React.useState(false);

    const canSubmit = currentPassword.length > 0 && newPassword.length > 0 && !saving;

    const submit = () => {
      if (!canSubmit) return;
      setSaving(true);
      setError(null);
      setJustSaved(false);
      // Simulate API call
      setTimeout(() => {
        setCurrentPassword("");
        setNewPassword("");
        setJustSaved(true);
        setSaving(false);
      }, 800);
    };

    return (
      <CardFrame
        title="Local admin password"
        subtitle="Change the password for your local admin account."
      >
        {error && (
          <div style={{
            display: "flex",
            alignItems: "flex-start",
            gap: 10,
            padding: "12px 14px",
            borderRadius: "var(--radius-md)",
            backgroundColor: "var(--ctv-warn-soft)",
            border: "1px solid var(--status-warn)",
            color: "var(--text-primary)"
          }}>
            <Ico n="TriangleAlert" s={15} color="var(--status-warn)" style={{ flexShrink: 0, marginTop: 2 }} />
            <span style={{ font: "var(--text-sm)/1.3 var(--font-sans)" }}>
              {error}
            </span>
          </div>
        )}

        {/* Form fields */}
        <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: error ? 12 : 0 }}>
          <Input
            label="Current password"
            type="password"
            value={currentPassword}
            onChange={(e) => {
              setCurrentPassword(e.target.value);
              setJustSaved(false);
            }}
            leadingIcon={<Ico n="Lock" s={14} />}
            placeholder="Enter your current password"
          />
          <Input
            label="New password"
            type="password"
            value={newPassword}
            onChange={(e) => {
              setNewPassword(e.target.value);
              setJustSaved(false);
            }}
            leadingIcon={<Ico n="Lock" s={14} />}
            placeholder="Enter your new password"
          />
        </div>

        {/* Action bar */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, marginTop: 16 }}>
          {justSaved && (
            <span style={{
              display: "inline-flex",
              alignItems: "center",
              gap: 6,
              font: "var(--weight-medium) var(--text-sm)/1 var(--font-sans)",
              color: "var(--status-ok)"
            }}>
              <Ico n="Check" s={14} />
              Password changed.
            </span>
          )}
          {!justSaved && <span />}
          <Button
            size="sm"
            variant="primary"
            startIcon={<Ico n="Check" s={14} />}
            onClick={submit}
            disabled={!canSubmit}
            loading={saving}
          >
            {saving ? "Changing…" : "Change password"}
          </Button>
        </div>
      </CardFrame>
    );
  }

  function ApiKey() {
    return (
      <div style={{
        display: "flex",
        flexDirection: "column",
        height: "100%",
        gap: 16,
        padding: "20px",
        overflow: "auto"
      }}>
        <MachineKeyCard />
        {mockAuthMethod === "local" && <LocalPasswordCard />}
      </div>
    );
  }

  window.CTVApiKey = ApiKey;
})();
