// Settings — three tabs: Profile, Compliance, Automation.

const Settings = ({ width = 1440, height = 980 }) => {
  const connected = (typeof useConnected === "function") ? useConnected() : null;
  const [tab, setTab] = React.useState("compliance");
  // Right-side panel for the Automation view: always one of "preview" | "file".
  const [viewTab, setViewTab] = React.useState("preview");

  const TABS = [
    { k: "compliance", label: "Compliance" },
    { k: "profile",    label: "Profile" },
    { k: "automation", label: "Automation" },
  ];

  const HEADERS = {
    profile:    { eyebrow: "Account",                          title: "Your profile" },
    compliance: { eyebrow: "Compliance · rule set",            title: "How should RedGone judge your team?" },
    automation: { eyebrow: "Automation · how RedGone runs your inbox", title: "Tell RedGone what emails it can answer." },
  };
  const header = HEADERS[tab];

  return (
    <div style={{
      width, height, background: "var(--white-pure)",
      display: "flex", flexDirection: "column", overflow: "hidden",
    }}>
      <TopBar active="Settings"/>

      {/* Top row — main tabs + inline page header + (Automation) view tabs */}
      <div style={{
        padding: "20px 32px 14px",
        display: "flex", alignItems: "center", gap: 24,
        flexShrink: 0,
      }}>
        <div className="rg-tabs" style={{ flexShrink: 0 }}>
          {TABS.map(t => (
            <button
              key={t.k}
              onClick={() => setTab(t.k)}
              className={`rg-tab ${tab === t.k ? "on" : ""}`}
            >
              {t.label}
            </button>
          ))}
        </div>

        <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", lineHeight: 1.15 }}>
          <span className="micro" style={{ marginBottom: 2 }}>{header.eyebrow}</span>
          <span style={{
            fontFamily: "Manrope, Plus Jakarta Sans, Inter, sans-serif",
            fontSize: 19, fontWeight: 600, letterSpacing: "-0.015em",
            color: "var(--midnight)",
            whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
          }}>{header.title}</span>
        </div>

        {tab === "automation" && (
          <div className="rg-tabs" style={{ flexShrink: 0 }}>
            <button
              onClick={() => setViewTab("preview")}
              className={`rg-tab ${viewTab === "preview" ? "on" : ""}`}
            >Spec preview</button>
            <button
              onClick={() => setViewTab("file")}
              className={`rg-tab ${viewTab === "file" ? "on" : ""}`}
            >Instruction file</button>
          </div>
        )}
      </div>

      <div style={{
        flex: 1,
        overflow: "hidden", minHeight: 0,
        display: "flex", flexDirection: "column",
      }}>
        {tab === "compliance" && <ComplianceTab/>}
        {tab === "profile"    && <ProfileTab connected={connected}/>}
        {tab === "automation" && <AutomationTab viewTab={viewTab}/>}
      </div>
    </div>
  );
};

// ──────────────────────────────────────────────────────────────────────
// Profile tab
// ──────────────────────────────────────────────────────────────────────
const ProfileTab = ({ connected }) => {
  const [name, setName] = React.useState(() => connected ? connected.name : "");
  const [email, setEmail] = React.useState(() => connected ? connected.email : "");
  const [anthropicKey, setAnthropicKey] = React.useState("");
  const [anthropicModel, setAnthropicModel] = React.useState("claude-opus-4-7");

  const isConnected = !!connected;

  const onLogOut = () => {
    if (typeof setConnected === "function") setConnected(null);
  };

  return (
    <div className="scroll-hidden" style={{
      width: "100%", display: "flex", flexDirection: "column", gap: 24,
      overflow: "auto", minHeight: 0,
      padding: "8px 32px 40px",
    }}>
      <div className="body" style={{ color: "var(--midnight-soft)", maxWidth: 540 }}>
        {isConnected
          ? "We pulled this from your Gmail. Update anything and we'll use it across the product."
          : "You're in demo mode. Connect your inbox to personalize this."}
      </div>

      <div className="pillow" style={{ padding: 28, display: "flex", flexDirection: "column", gap: 18 }}>
        <ProfileField
          label="Display name"
          value={name}
          onChange={setName}
          disabled={!isConnected}
          placeholder="Your full name"
        />
        <ProfileField
          label="Email"
          value={email}
          onChange={setEmail}
          disabled
          placeholder="you@gmail.com"
        />
        <ProfileField
          label="Role"
          value={isConnected ? "Compliance analyst" : ""}
          onChange={() => {}}
          disabled
          placeholder="Add your role"
        />

        <div style={{ display: "flex", justifyContent: "flex-end", alignItems: "center", gap: 10 }}>
          {!isConnected && (
            <a href="/connect" data-link className="neu-btn-redglow neu-btn-redglow-sm">
              <span>Connect Email</span>
              <span style={{ opacity: 0.85 }}>→</span>
            </a>
          )}
          <button
            disabled={!isConnected}
            className={isConnected ? "neu-btn neu-btn-primary neu-btn-sm" : "neu-btn-muted"}
            style={isConnected
              ? null
              : { padding: "8px 14px", fontSize: 12, borderRadius: 10 }}
          >Save changes</button>
        </div>
      </div>

      {/* AI provider — only when logged in. Anthropic is wired up; OpenAI/Google are stubs. */}
      {isConnected && (
        <div className="pillow" style={{ padding: 28 }}>
          <div className="micro">AI provider</div>
          <div className="h3" style={{ marginTop: 8 }}>Bring your own key.</div>
          <div className="body" style={{ color: "var(--midnight-soft)", marginTop: 8, maxWidth: 540 }}>
            RedGone runs your compliance scoring through your AI provider. Anthropic is wired up — others are coming.
          </div>

          <div style={{ marginTop: 22, display: "flex", flexDirection: "column", gap: 22 }}>
            <ProviderBlock name="Anthropic" status="ACTIVE" hint="Claude — live compliance scoring.">
              <ProfileField
                label="API key"
                value={anthropicKey}
                onChange={setAnthropicKey}
                placeholder="sk-ant-..."
                type="password"
              />
              <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                <span className="micro">Model</span>
                <select
                  value={anthropicModel}
                  onChange={(e) => setAnthropicModel(e.target.value)}
                  className="neu-input"
                  style={{ cursor: "pointer" }}
                >
                  <option value="claude-opus-4-7">Claude Opus 4.7 — most capable</option>
                  <option value="claude-sonnet-4-6">Claude Sonnet 4.6 — balanced</option>
                  <option value="claude-haiku-4-5">Claude Haiku 4.5 — fastest</option>
                </select>
              </label>
            </ProviderBlock>

            <ProviderBlock name="OpenAI" status="SOON" hint="GPT — coming soon.">
              <ProfileField label="API key" value="" onChange={() => {}} disabled placeholder="sk-..." type="password"/>
            </ProviderBlock>

            <ProviderBlock name="Google" status="SOON" hint="Gemini — coming soon.">
              <ProfileField label="API key" value="" onChange={() => {}} disabled placeholder="AIza..." type="password"/>
            </ProviderBlock>
          </div>
        </div>
      )}

      {/* Log out — bottom of the Profile tab */}
      {isConnected && (
        <div style={{ display: "flex", justifyContent: "flex-start", paddingTop: 8 }}>
          <button onClick={onLogOut} className="neu-btn" style={{
            color: "var(--red-deep)",
            border: "1px solid rgba(185, 28, 44, 0.25)",
            display: "inline-flex", alignItems: "center", gap: 8,
            padding: "10px 18px",
          }}>
            <span>Log out</span>
            <span style={{ opacity: 0.6 }}>→</span>
          </button>
        </div>
      )}
    </div>
  );
};

const ProfileField = ({ label, value, onChange, disabled, placeholder, type = "text" }) => (
  <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
    <span className="micro">{label}</span>
    <input
      type={type}
      value={value}
      onChange={(e) => onChange(e.target.value)}
      disabled={disabled}
      placeholder={placeholder}
      className="neu-input"
      autoComplete={type === "password" ? "off" : undefined}
      spellCheck={type === "password" ? false : undefined}
      style={{
        opacity: disabled ? 0.7 : 1,
        cursor: disabled ? "default" : "text",
        fontFamily: type === "password" ? "'JetBrains Mono', monospace" : undefined,
        letterSpacing: type === "password" ? "0.15em" : undefined,
      }}
    />
  </label>
);

const ProviderBlock = ({ name, status, hint, children }) => {
  const active = status === "ACTIVE";
  return (
    <div style={{
      display: "flex", flexDirection: "column", gap: 12,
      opacity: active ? 1 : 0.55,
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
        <span style={{
          width: 8, height: 8, borderRadius: 999,
          background: active ? "var(--success-mint)" : "var(--gray-whisper)",
          boxShadow: active ? "0 0 0 4px rgba(52,211,153,0.18)" : "none",
        }}/>
        <span style={{ fontSize: 14, fontWeight: 600 }}>{name}</span>
        <span className="mono" style={{
          fontSize: 10, letterSpacing: "0.08em",
          color: active ? "var(--success-mint)" : "var(--midnight-soft)",
        }}>{status}</span>
        <span className="small" style={{
          color: "var(--midnight-soft)", fontSize: 12, marginLeft: "auto",
        }}>{hint}</span>
      </div>
      {children}
    </div>
  );
};

// ──────────────────────────────────────────────────────────────────────
// Compliance tab — original settings content
// ──────────────────────────────────────────────────────────────────────
const ComplianceTab = () => {
  const [active, setActive] = React.useState("FCA");

  const modes = [
    { k: "FCA", title: "FCA", sub: "Financial Conduct Authority",
      desc: "Communications must be fair, clear, balanced, and not misleading. Catches absolute claims, missing risk warnings, and unhedged forecasts.", icon: "⚖" },
    { k: "SEC", title: "SEC", sub: "U.S. Securities & Exchange Commission",
      desc: "Investment language, performance claims, and risk disclosures. Enforces Rule 482 and anti-fraud provisions in client communications.", icon: "★" },
    { k: "Internal", title: "Internal Policy", sub: "Company-uploaded rules",
      desc: "Banned phrases, required disclaimers, escalation triggers — defined by your compliance team and applied across the firm.", icon: "◆" },
  ];

  return (
    <div className="scroll-hidden" style={{
      display: "flex", flexDirection: "column", gap: 24,
      overflow: "auto", minHeight: 0,
      padding: "8px 32px 40px",
    }}>
      <div style={{ display: "flex", justifyContent: "flex-end" }}>
        <span className="mono" style={{ fontSize: 11, color: "var(--midnight-soft)" }}>3 MODES · 1 ACTIVE</span>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 24 }}>
        {modes.map(m => {
          const on = m.k === active;
          return (
            <div key={m.k} className="pillow" onClick={() => setActive(m.k)} style={{
              padding: 28, cursor: "pointer", position: "relative",
              border: on ? "1px solid rgba(230,57,70,0.35)" : "1px solid rgba(10,22,40,0.03)",
              boxShadow: on
                ? "0 1px 2px rgba(230,57,70,0.06), 0 8px 24px rgba(230,57,70,0.10), 0 24px 48px rgba(10,22,40,0.04)"
                : "var(--pillow-shadow)",
              transition: "all 280ms var(--ease-soft)",
            }}>
              {on && (
                <div style={{
                  position: "absolute", inset: 0, borderRadius: 20,
                  background: "linear-gradient(135deg, rgba(230,57,70,0.06), rgba(244,196,48,0.04))",
                  pointerEvents: "none",
                }}/>
              )}
              <div style={{ position: "relative" }}>
                <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between" }}>
                  <div style={{
                    width: 44, height: 44, borderRadius: 12,
                    background: "var(--white-soft)",
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontSize: 20, color: "var(--midnight)",
                  }}>{m.icon}</div>
                  <div className={`neu-toggle ${on ? "on" : ""}`}>
                    <div className="knob"/>
                  </div>
                </div>
                <div className="h2" style={{ marginTop: 20 }}>{m.title}</div>
                <div className="micro" style={{ color: "var(--midnight-soft)", marginTop: 4 }}>{m.sub}</div>
                <div className="body" style={{ color: "var(--midnight-soft)", marginTop: 14 }}>{m.desc}</div>

                <div style={{ display: "flex", gap: 10, marginTop: 22, paddingTop: 18, borderTop: "1px solid var(--gray-whisper)" }}>
                  <Stat label="Avg score" value={m.k === "FCA" ? "92" : m.k === "SEC" ? "87" : "94"}/>
                  <Stat label="Rules" value={m.k === "FCA" ? "146" : m.k === "SEC" ? "212" : "38"}/>
                  <Stat label="Updated" value={m.k === "Internal" ? "Today" : "Apr"}/>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Internal expansion */}
      {active === "Internal" && (
        <div className="pillow float-in" style={{ padding: 32, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24 }}>
          <div>
            <div className="micro">Internal · custom rules</div>
            <div className="h2" style={{ marginTop: 8 }}>Upload your firm's policy.</div>
            <div className="body" style={{ color: "var(--midnight-soft)", marginTop: 10 }}>
              Drop a PDF, DOCX, or paste rules below. RedGone parses banned phrases, required disclaimers, and
              escalation triggers, and starts scoring against them within minutes.
            </div>
            <div style={{
              marginTop: 16, padding: 24, borderRadius: 14,
              border: "1.5px dashed var(--gray-whisper)", background: "var(--white-soft)",
              textAlign: "center", color: "var(--midnight-soft)",
            }}>
              <div className="small" style={{ color: "var(--midnight)", fontWeight: 600 }}>Drop a policy file</div>
              <div className="mono" style={{ fontSize: 11, marginTop: 4 }}>PDF · DOCX · MD · up to 25 MB</div>
            </div>
          </div>
          <div>
            <div className="micro">Or paste rules</div>
            <textarea
              defaultValue={`# Northwind compliance — internal policy v3.2
ban: "guaranteed", "risk-free", "can't lose", "definitely will"
require_disclaimer:
  - on: forward_looking_statement
    text: "Forward-looking statements are subject to risk."
escalate:
  - if: complaint OR regulator OR press
    to: compliance@northwind-cap.com`}
              spellCheck={false}
              className="scroll"
              style={{
                width: "100%", marginTop: 8, padding: 16, borderRadius: 14, height: 220,
                background: "var(--white-soft)", fontSize: 13, lineHeight: 1.6,
                fontFamily: "'JetBrains Mono', monospace", color: "var(--midnight-soft)",
                border: "none", outline: "none", resize: "vertical",
                boxShadow: "var(--neu-in)",
              }}
            />
            <div style={{ display: "flex", gap: 10, marginTop: 12, justifyContent: "flex-end" }}>
              <button className="neu-btn neu-btn-sm">Validate</button>
              <button className="neu-btn neu-btn-primary neu-btn-sm">Apply rules</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ──────────────────────────────────────────────────────────────────────
// Automation tab — conversational rule crafting. Spec preview / instruction
// file editor live inside the SpecBuilder's drawer (opened from a menu icon
// inside the convo).
// ──────────────────────────────────────────────────────────────────────
const AutomationTab = ({ viewTab }) => {
  return (
    <div style={{
      display: "flex", flexDirection: "column",
      height: "100%", minHeight: 0,
      padding: "0 32px 24px",
    }}>
      <div style={{ flex: 1, minHeight: 0, position: "relative" }}>
        <SpecBuilder bare viewTab={viewTab}/>
      </div>
    </div>
  );
};

// RawSpecEditor moved to spec-builder.jsx as InstructionFileEditor — opened
// from the menu drawer inside the SpecBuilder convo.

const Stat = ({ label, value }) => (
  <div style={{ flex: 1 }}>
    <div className="micro" style={{ color: "var(--midnight-soft)" }}>{label}</div>
    <div style={{ fontSize: 18, fontWeight: 600, marginTop: 4, color: "var(--midnight)" }}>{value}</div>
  </div>
);

window.Settings = Settings;
