/* =========================================================================
   Veto · Settings — Office / Reviewers / Money evidence / Policy / Labs
   Labs = experimental features, off by default.
   ========================================================================= */

function Switch({ on, onChange }) {
  return (
    <button type="button" role="switch" aria-checked={on} onClick={() => onChange(!on)}
      className={cn("relative inline-flex h-[22px] w-[38px] shrink-0 cursor-pointer items-center rounded-full transition-colors", on ? "bg-ink" : "bg-surface-2")}>
      <span className={cn("inline-block h-[18px] w-[18px] rounded-full bg-background shadow transition-transform", on ? "translate-x-[18px]" : "translate-x-[2px]")} />
    </button>
  );
}

function Segmented({ value, onChange, options }) {
  return (
    <div className="inline-flex items-center rounded-lg border border-line bg-surface/70 p-0.5">
      {options.map((o) => (
        <button key={o.value} type="button" onClick={() => onChange(o.value)}
          className={cn("rounded-md px-3.5 py-1.5 text-[12.5px] font-medium transition", value === o.value ? "bg-background text-ink shadow-sm" : "text-ink-soft hover:text-ink")}>
          {o.label}
        </button>
      ))}
    </div>
  );
}

function ToggleRow({ title, note, on, onChange, badge }) {
  return (
    <div className="flex items-start justify-between gap-6 py-4">
      <div className="min-w-0">
        <div className="flex items-center gap-2">
          <span className="text-[13.5px] font-medium text-ink">{title}</span>
          {badge && <span className="rounded bg-surface-2 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-[0.04em] text-ink-soft">{badge}</span>}
        </div>
        <p className="mt-1 max-w-[440px] text-[12.5px] leading-relaxed text-ink-soft">{note}</p>
      </div>
      <Switch on={on} onChange={onChange} />
    </div>
  );
}

function SettingsField({ label, value, mono }) {
  return (
    <label className="block">
      <span className="mb-1.5 block text-[12.5px] font-medium text-ink">{label}</span>
      <input defaultValue={value}
        className={cn("h-10 w-full rounded-lg border border-line bg-background px-3 text-[13.5px] text-ink outline-none transition focus:border-ink/40 focus:ring-1 focus:ring-ink/15", mono && "font-mono")} />
    </label>
  );
}

const SETTINGS_TABS = [
  { key: "office", label: "Office", icon: "building" },
  { key: "security", label: "Security", icon: "lock" },
  { key: "reviewers", label: "Reviewers", icon: "users" },
  { key: "money", label: "Money evidence", icon: "shield-check" },
  { key: "policy", label: "Policy", icon: "scale" },
  { key: "labs", label: "Labs", icon: "beaker" },
];

const SETTINGS_REVIEWER_EMAILS = {
  OP: "owner@805escrow.example",
  ML: "madeline.lane@805escrow.example",
  JR: "javier.reyes@805escrow.example",
  AK: "anita.kuroda@805escrow.example",
};

function Settings({ initialTab }) {
  const [tab, setTab] = useState(initialTab || "office");
  const [branches, setBranches] = useState(["Westlake Village"]);
  const [newBranch, setNewBranch] = useState("");
  const [transfer, setTransfer] = useState(false);
  const [owner, setOwner] = useState("OP");
  const [twofaRequired, setTwofaRequired] = useState(true);
  const [emailFallback, setEmailFallback] = useState(false);
  const [domainJoin, setDomainJoin] = useState("request");
  const [labs, setLabs] = useState(() => {
    let palette = false; try { palette = localStorage.getItem("veto.labs.palette") === "1"; } catch {}
    return { v2receipt: false, autocallback: false, keyboardFirst: false, conflictRadar: false, paletteEverywhere: palette };
  });
  const setLab = (k, v) => {
    setLabs((s) => ({ ...s, [k]: v }));
    if (k === "paletteEverywhere") { try { localStorage.setItem("veto.labs.palette", v ? "1" : "0"); } catch {} }
  };

  return (
    <AppShell activeLine="settings">
      <div className="mx-auto w-full max-w-[1000px] px-6 py-10 lg:px-12 lg:py-12">
        <h1 className="text-[26px] font-semibold tracking-[-0.02em] text-ink">Settings</h1>
        <p className="mt-1 text-[13px] text-ink-soft">805 Escrow · Westlake Village</p>

        {/* Top tab bar */}
        <nav className="mt-7 flex items-center gap-6 overflow-x-auto border-b border-line">
          {SETTINGS_TABS.map((t) => (
            <button key={t.key} type="button" onClick={() => setTab(t.key)}
              className={cn("-mb-px flex shrink-0 cursor-pointer items-center gap-2 border-b-[1.5px] py-3 text-[13.5px] transition",
                tab === t.key ? "border-ink font-medium text-ink" : "border-transparent text-ink-soft hover:text-ink")}>
              <Icon name={t.icon} size={15} className="shrink-0" /> {t.label}
            </button>
          ))}
        </nav>

        <div className="mt-8 max-w-[620px]">
          {/* panel */}
          <div className="min-w-0">
            {tab === "office" && (
              <Panel title="Office" note="The office owns every file, reviewer, and receipt.">
                <div className="grid max-w-[460px] gap-4">
                  <SettingsField label="Office name" value="805 Escrow" />
                  <SettingsField label="License number" value="CA-ESCROW-0042118" mono />
                </div>

                {/* Branches */}
                <div className="mt-8 border-t border-line pt-6">
                  <h3 className="text-[13.5px] font-medium text-ink">Branches</h3>
                  <p className="mt-1 max-w-[460px] text-[12.5px] text-ink-soft">Group files and reviewers by where they close. Most offices have one; add more if you close out of several locations.</p>
                  <ul className="mt-4 max-w-[460px] divide-y divide-line">
                    {branches.map((b) => (
                      <li key={b} className="flex items-center gap-3 py-2.5">
                        <Icon name="building" size={15} className="shrink-0 text-ink-soft" />
                        <span className="flex-1 text-[13.5px] text-ink">{b}</span>
                        <button onClick={() => setBranches((l) => (l.length === 1 ? l : l.filter((x) => x !== b)))} disabled={branches.length === 1} aria-label={"Remove " + b}
                          className="grid h-7 w-7 place-items-center rounded-md text-muted-foreground transition hover:bg-surface hover:text-ink disabled:opacity-30"><Icon name="x" size={14} /></button>
                      </li>
                    ))}
                  </ul>
                  <div className="mt-3 flex max-w-[460px] items-center gap-2">
                    <input value={newBranch} onChange={(e) => setNewBranch(e.target.value)}
                      onKeyDown={(e) => { if (e.key === "Enter" && newBranch.trim()) { setBranches((l) => [...l, newBranch.trim()]); setNewBranch(""); } }}
                      placeholder="Add a branch — e.g. Irvine"
                      className="h-10 flex-1 rounded-lg border border-line bg-background px-3 text-[13.5px] text-ink outline-none transition focus:border-ink/40 focus:ring-1 focus:ring-ink/15" />
                    <button onClick={() => { if (newBranch.trim()) { setBranches((l) => [...l, newBranch.trim()]); setNewBranch(""); } }}
                      className="inline-flex h-10 items-center gap-1.5 rounded-lg bg-ink px-3.5 text-[12.5px] font-medium text-background hover:bg-ink/90"><Icon name="plus" size={13} strokeWidth={2} /> Add</button>
                  </div>
                </div>

                {/* Ownership */}
                <div className="mt-8 border-t border-line pt-6">
                  <h3 className="text-[13.5px] font-medium text-ink">Ownership</h3>
                  <p className="mt-1 max-w-[460px] text-[12.5px] text-ink-soft">The owner controls billing, security, and can hand the office to someone else. Whoever creates the office is owner by default — it isn't tied to a signing role.</p>
                  <div className="mt-4 flex max-w-[460px] items-center gap-3 rounded-xl border border-line bg-surface/40 p-3">
                    <span className="grid h-9 w-9 place-items-center rounded-full bg-surface-2 text-[12px] font-medium text-ink">OP</span>
                    <div className="min-w-0 flex-1">
                      <div className="text-[13.5px] text-ink">Office Principal <span className="text-ink-soft">· Owner / Principal</span></div>
                      <div className="text-[12px] text-ink-soft">Owner / Principal · 805 Escrow</div>
                    </div>
                    <button onClick={() => setTransfer((t) => !t)} className="rounded-lg border border-line px-3 py-1.5 text-[12.5px] font-medium text-ink transition hover:bg-surface">Transfer</button>
                  </div>
                  {transfer && (
                    <div className="mt-2 max-w-[460px] overflow-hidden rounded-xl border border-line">
                      {Object.values(REVIEWERS).filter((r) => r.initials !== "OP").map((r) => (
                        <button key={r.initials} onClick={() => { setOwner(r.initials); setTransfer(false); }}
                          className="flex w-full items-center gap-3 border-b border-line px-3 py-2.5 text-left transition last:border-0 hover:bg-surface">
                          <span className="grid h-8 w-8 place-items-center rounded-full bg-surface-2 text-[11px] font-medium text-ink">{r.initials}</span>
                          <span className="min-w-0 flex-1"><span className="block text-[13px] text-ink">{r.name}</span><span className="block text-[11.5px] text-ink-soft">{r.roleLabel}</span></span>
                          <span className="text-[11.5px] font-medium text-ink-soft">Make owner</span>
                        </button>
                      ))}
                    </div>
                  )}
                  {owner !== "OP" && <p className="mt-2 max-w-[460px] text-[12px] text-[var(--ok)]">Transfer queued. {REVIEWERS[owner]?.name} must accept before it takes effect. The current owner stays owner until then.</p>}
                </div>
              </Panel>
            )}

            {tab === "security" && (
              <Panel title="Security" note="How people prove who they are, and who's allowed to join.">
                {/* Two-factor */}
                <div>
                  <h3 className="text-[13.5px] font-medium text-ink">Two-factor authentication</h3>
                  <p className="mt-1 max-w-[460px] text-[12.5px] text-ink-soft">An emailed code alone is phishable. Veto adds a second factor — a passkey or authenticator app — on every sign-in.</p>
                  <div className="mt-4 divide-y divide-line">
                    <ToggleRow title="Require two-factor for everyone" on={twofaRequired} onChange={setTwofaRequired}
                      note="Every reviewer enrols a passkey or authenticator before they can open a file. Strongly recommended." />
                    <ToggleRow title="Allow an emailed code as fallback" on={emailFallback} onChange={setEmailFallback}
                      note="Let a reviewer in with just an email code if they lose their device. Weaker — off by default." />
                  </div>
                  <div className="mt-4 flex max-w-[460px] items-center gap-3 rounded-xl border border-line bg-surface/40 p-3">
                    <Icon name="lock" size={16} className="shrink-0 text-ink-soft" />
                    <div className="min-w-0 flex-1">
                      <div className="text-[13.5px] text-ink">Your method · Passkey</div>
                      <div className="text-[12px] text-ink-soft">Touch ID on this device</div>
                    </div>
                    <button className="rounded-lg border border-line px-3 py-1.5 text-[12.5px] font-medium text-ink transition hover:bg-surface">Manage</button>
                  </div>
                </div>

                {/* Domain join */}
                <div className="mt-8 border-t border-line pt-6">
                  <h3 className="text-[13.5px] font-medium text-ink">Joining by email domain</h3>
                  <p className="mt-1 max-w-[460px] text-[12.5px] text-ink-soft">What happens when someone with a <span className="font-mono text-ink">@805escrow.example</span> address tries to join your office.</p>
                  <div className="mt-4"><Segmented value={domainJoin} onChange={setDomainJoin}
                    options={[{ value: "off", label: "Off" }, { value: "request", label: "Request to join" }, { value: "auto", label: "Auto-join" }]} /></div>
                  <p className="mt-3 max-w-[460px] text-[12.5px] leading-relaxed text-ink-soft">
                    {domainJoin === "off" && "Only people you invite by email can join. Most secure."}
                    {domainJoin === "request" && "Matching addresses can request access; an owner or manager must accept each request."}
                    {domainJoin === "auto" && "Anyone with a matching address joins instantly as an assistant — they can prep files but not sign. An owner promotes them when ready."}
                  </p>
                </div>
              </Panel>
            )}

            {tab === "reviewers" && (
              <Panel title="Reviewers" note="People who can open files and sign receipts.">
                <div className="mb-6 overflow-hidden rounded-xl border border-line">
                  <div className="border-b border-line bg-surface/40 px-4 py-3">
                    <h3 className="text-[13.5px] font-medium text-ink">Roles & permissions</h3>
                    <p className="mt-1 text-[12.5px] text-ink-soft">Three levels in this office. Exceptions are recorded — never silent.</p>
                  </div>
                  <ul className="divide-y divide-line">
                    <li className="flex items-start justify-between gap-4 px-4 py-3.5">
                      <div className="min-w-0">
                        <div className="text-[13.5px] font-medium text-ink">Owner / Principal <span className="font-normal text-ink-soft">· Office Principal</span></div>
                        <p className="mt-1 text-[12.5px] text-ink-soft">Full oversight and record exceptions. Review Register included.</p>
                      </div>
                      <Switch on={true} onChange={() => {}} />
                    </li>
                    <li className="flex items-start justify-between gap-4 px-4 py-3.5">
                      <div className="min-w-0">
                        <div className="text-[13.5px] font-medium text-ink">Escrow officer <span className="font-normal text-ink-soft">· Madeline Lane</span></div>
                        <p className="mt-1 text-[12.5px] text-ink-soft">File work and receipts. Review Register hidden.</p>
                      </div>
                      <Switch on={true} onChange={() => {}} />
                    </li>
                    <li className="flex items-start justify-between gap-4 px-4 py-3.5">
                      <div className="min-w-0">
                        <div className="text-[13.5px] font-medium text-ink">Branch manager <span className="font-normal text-ink-soft">· Javier Reyes</span></div>
                        <p className="mt-1 text-[12.5px] text-ink-soft">Exception authority on operational conflicts — not owner-level payout holds.</p>
                      </div>
                      <Switch on={true} onChange={() => {}} />
                    </li>
                  </ul>
                </div>
                <ul className="divide-y divide-line">
                  {Object.values(REVIEWERS).map((r) => (
                    <li key={r.initials} className="flex items-center gap-3 py-3.5">
                      <span className="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-surface-2 text-[12px] font-medium text-ink">{r.initials}</span>
                      <div className="min-w-0 flex-1">
                        <div className="text-[13.5px] text-ink">{r.name}</div>
                        <div className="text-[12px] text-ink-soft">{SETTINGS_REVIEWER_EMAILS[r.initials] ?? r.email}</div>
                      </div>
                      <span className="rounded-md border border-line px-2.5 py-1 text-[11.5px] text-ink-soft">{r.roleLabel}</span>
                    </li>
                  ))}
                </ul>
                <button className="mt-4 inline-flex items-center gap-1.5 rounded-md bg-ink px-3.5 py-2 text-[12.5px] font-medium text-background hover:bg-ink/90"><Icon name="plus" size={13} strokeWidth={2} /> Invite reviewer</button>
              </Panel>
            )}

            {tab === "money" && (
              <Panel title="Money evidence" note="What each money line must establish before recording.">
                <div className="divide-y divide-line">
                  <ToggleRow title="Independent callback required" on note="Every destination wire is reviewed at a number not supplied by the demand." onChange={() => {}} />
                  <ToggleRow title="Incoming-funds hold" on note="Buyer funding evidence and collection status must be recorded before a line can record." onChange={() => {}} />
                  <ToggleRow title="Per-diem freshness check" on note="Payoff demand must be current through the closing date." onChange={() => {}} />
                </div>
              </Panel>
            )}

            {tab === "policy" && (
              <Panel title="Policy" note="The office's standing positions. Exceptions are recorded, never silent.">
                <PolicyControlCard control={typeof getPolicyControl === "function" ? getPolicyControl("seller.destination.v2") : null} />
                <div className="mt-6 divide-y divide-line border-t border-line">
                  <ToggleRow title="Manager exception requires second signer" on note="A manager exception on a conflict needs a second reviewer to co-sign." onChange={() => {}} />
                  <ToggleRow title="Block release on stale support record" badge="Core" on note="No release request can proceed while a material change has staled the support record." onChange={() => {}} />
                  <ToggleRow title="Restricted reviewers are read-only" on note="Restricted role can view files and receipts but cannot sign." onChange={() => {}} />
                </div>
              </Panel>
            )}

            {tab === "labs" && (
              <Panel title="Labs" note="Experimental features. Off by default. Turn on at your own risk.">
                <div className="mb-4 flex items-start gap-2.5 rounded-lg border border-[var(--warn)]/25 bg-[var(--warn-bg)] px-3.5 py-3">
                  <Icon name="beaker" size={15} className="mt-0.5 shrink-0 text-[var(--warn)]" />
                  <p className="text-[12.5px] leading-relaxed text-ink">These change how the console behaves and may change or disappear. Nothing here affects the receipt record.</p>
                </div>
                <div className="divide-y divide-line">
                  <ToggleRow title="Receipt v2 layout" badge="Alpha" on={labs.v2receipt} onChange={(v) => setLab("v2receipt", v)}
                    note="A denser, source-grouped receipt with inline evidence provenance." />
                  <ToggleRow title="Auto-callback reminders" badge="Alpha" on={labs.autocallback} onChange={(v) => setLab("autocallback", v)}
                    note="Nudge the reviewer when a callback checkpoint has been open too long." />
                  <ToggleRow title="Conflict radar" badge="Experimental" on={labs.conflictRadar} onChange={(v) => setLab("conflictRadar", v)}
                    note="Surface likely conflicts across lines before you open the file." />
                  <ToggleRow title="Keyboard-first mode" badge="Experimental" on={labs.keyboardFirst} onChange={(v) => setLab("keyboardFirst", v)}
                    note="Record checkpoints without leaving the keyboard. Adds j/k navigation." />
                </div>
              </Panel>
            )}
          </div>
        </div>
      </div>
    </AppShell>
  );
}

function Panel({ title, note, children }) {
  return (
    <section>
      <div className="border-b border-line pb-4">
        <h2 className="text-[16px] font-semibold tracking-[-0.01em] text-ink">{title}</h2>
        <p className="mt-1 text-[12.5px] text-ink-soft">{note}</p>
      </div>
      <div className="pt-5">{children}</div>
    </section>
  );
}

function PolicyControlCard({ control }) {
  if (!control) return null;
  const rows = [
    ["Action controlled", control.actionControlled],
    ["Trigger", control.trigger],
    ["Scope", control.scope],
    ["Effect", control.effect],
    ["Exception path", control.exceptionPath],
    ["Approver role", control.approverRole],
    ["Receipt visibility", control.receiptVisibility],
  ];
  return (
    <div className="overflow-hidden rounded-xl border border-line bg-background">
      <div className="border-b border-line bg-surface/40 px-4 py-3.5">
        <div className="flex flex-wrap items-center gap-2">
          <span className="inline-flex items-center gap-1.5 rounded-full bg-[var(--ok-bg)] px-2 py-0.5 text-[11px] font-medium text-[var(--ok)]">
            <span className="h-1.5 w-1.5 rounded-full bg-[var(--ok)]" />Active
          </span>
          {control.core && <span className="rounded-full border border-line bg-background px-2 py-0.5 text-[10.5px] text-muted-foreground">Core control</span>}
          {control.downgradeLogged && <span className="rounded-full border border-line bg-background px-2 py-0.5 text-[10.5px] text-muted-foreground">Downgrade logged</span>}
        </div>
        <div className="mt-2 text-[13.5px] font-medium text-ink">{control.name}</div>
        <div className="mt-1 font-mono text-[11px] text-muted-foreground">{control.version} · effective {control.effectiveDate} · {control.changedBy}</div>
      </div>
      <div className="divide-y divide-line">
        {rows.map(([k, v]) => (
          <div key={k} className="grid grid-cols-[150px_minmax(0,1fr)] gap-3 px-4 py-3 text-[12.5px]">
            <div className="text-muted-foreground">{k}</div>
            <div className="leading-relaxed text-ink">{v}</div>
          </div>
        ))}
      </div>
      <div className="grid grid-cols-1 gap-0 border-t border-line md:grid-cols-2 md:divide-x md:divide-line">
        <div className="px-4 py-3">
          <div className="text-[10.5px] uppercase tracking-[0.06em] text-muted-foreground">Required evidence</div>
          <ul className="mt-2 space-y-1.5">
            {control.requiredEvidence.map((e) => <li key={e} className="flex items-start gap-2 text-[12px] text-ink"><span className="mt-[5px] h-1 w-1 shrink-0 rounded-full bg-ink-soft" />{e}</li>)}
          </ul>
        </div>
        <div className="px-4 py-3">
          <div className="text-[10.5px] uppercase tracking-[0.06em] text-muted-foreground">Source limitations</div>
          <ul className="mt-2 space-y-1.5">
            {control.requiredSourceLimitations.map((e) => <li key={e} className="flex items-start gap-2 text-[12px] text-ink-soft"><span className="mt-[5px] h-1 w-1 shrink-0 rounded-full bg-[var(--warn)]" />{e}</li>)}
          </ul>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Settings });
