// Teams — share your accuracy memory as portable, optionally-signed .rokkorpacks.
// Mirrors the desktop app's TeamsTab: Export, Import, Team signing key, Local API
// server. Privacy-first: everything stays local until you choose to share.
function TeamsScreen() {
  const { Button, Switch, Badge, StatCard } = window.ROKKORDesignSystem_4e99ef;
  const { Section, Inset, Select, Field, Notice } = window.RokkorKit;
  const I = window.RokkorIcons;

  // Established team — months of shared brain, fake but believable.
  const [payloads, setPayloads] = React.useState({ vocab: true, snippets: true, corrections: true, transforms: true });
  const togglePayload = (k) => (v) => setPayloads((p) => ({ ...p, [k]: v }));
  const [server, setServer] = React.useState(true);

  const counts = { vocab: 318, snippets: 64, corrections: 1242, transforms: 27 };

  const members = [
    ["Maya Renner", "maya@example.com", "Owner", "verified"],
    ["David Okafor", "david@example.com", "Maintainer", "verified"],
    ["Priya Shah", "priya@example.com", "Contributor", "verified"],
    ["Tomás Esquivel", "tomas@example.com", "Contributor", "verified"],
    ["Hannah Lindqvist", "hannah@example.com", "Reviewer", "verified"],
  ];

  const invites = [
    ["jordan@example.com", "Contributor", "sent 2 days ago"],
    ["wen@example.com", "Reviewer", "sent 6 days ago"],
  ];

  const recentPacks = [
    ["platform-vocab-2026-06.rokkorpack", "Maya Renner", "6/18/2026, 4:02 PM", "verified author", 281],
    ["onboarding-snippets.rokkorpack", "David Okafor", "6/15/2026, 10:21 AM", "verified author", 38],
    ["infra-corrections-q2.rokkorpack", "Priya Shah", "6/11/2026, 1:47 PM", "verified author", 906],
    ["legacy-glossary.csv", "imported CSV", "5/29/2026, 9:08 AM", "self-signed (author unverified)", 142],
  ];

  const pubKey = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE9pK2-team-rokkor-7Qf3xJ";

  const mono = { font: "12px/1 var(--font-mono)", color: "var(--ink-500)" };

  return (
    <div style={{ maxWidth: "var(--content-max)" }}>
      {/* Header */}
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between" }}>
        <div style={{ marginBottom: 26 }}>
          <h1 className="rk-display" style={{ font: "600 40px/1 var(--font-display)", letterSpacing: "0.035em", textTransform: "uppercase", display: "flex", alignItems: "center", gap: 14 }}>
            <span style={{ color: "var(--oxblood-600)" }}><I.Users size={30} /></span> Teams
            <span style={{ flex: 1, height: 2, background: "var(--rule-gold)", maxWidth: 130 }} />
          </h1>
          <p className="rk-subtitle" style={{ marginTop: 12, fontSize: 18 }}>
            Share your accuracy memory — corrections, snippets, vocabulary, and transforms — as a portable, optionally-signed .rokkorpack. Everything stays local until you choose to share.
          </p>
        </div>
        <div style={{ marginTop: 30 }}><Button variant="outline" icon={<I.Refresh size={15} />}>Refresh</Button></div>
      </div>

      {/* Privacy framing */}
      <div style={{ display: "flex", gap: 14, background: "var(--notice-bg)", border: "1px solid var(--notice-border)", borderRadius: "var(--radius-xl)", padding: "16px 18px", marginBottom: 24 }}>
        <div style={{ color: "var(--oxblood-700)", flex: "none", marginTop: 1 }}><I.Lock size={20} /></div>
        <div>
          <div style={{ font: "600 15px/1.3 var(--font-sans)", color: "var(--oxblood-700)" }}>No ROKKOR cloud — sharing is a file you control</div>
          <div style={{ font: "400 13px/1.5 var(--font-sans)", color: "var(--notice-body)", marginTop: 4 }}>
            Packs are plain .rokkorpack files you export, hand off, and import yourself. There is no account, no server, and no telemetry. Signing proves authorship with an ed25519 key — it never uploads anything.
          </div>
        </div>
      </div>

      {/* Shared brain stats */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16, marginBottom: 26 }}>
        <StatCard label="Vocabulary terms" value="318" note="Shared across the team" />
        <StatCard label="Corrections" value="1,242" note="Taught over 4 months" accent="gold" />
        <StatCard label="Snippets" value="64" note="Reusable phrases & templates" />
        <StatCard label="Transforms" value="27" note="Saved rewrite recipes" />
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
        {/* TEAM MEMBERS */}
        <Section icon={I.Users} title="Team" desc="People who share this brain. Roles are advisory labels on the pinned signing key — there is no central directory; membership is the set of keys your team trusts.">
          <Inset style={{ display: "flex", alignItems: "center", gap: 40, padding: "16px 20px", marginBottom: 16 }}>
            <span style={{ display: "flex", alignItems: "baseline", gap: 8 }}><b style={{ font: "600 18px/1 var(--font-serif)", color: "var(--oxblood-600)" }}>5</b><span style={{ font: "400 13px/1 var(--font-sans)", color: "var(--ink-600)" }}>Members</span></span>
            <span style={{ display: "flex", alignItems: "baseline", gap: 8 }}><b style={{ font: "600 18px/1 var(--font-serif)", color: "var(--oxblood-600)" }}>2</b><span style={{ font: "400 13px/1 var(--font-sans)", color: "var(--ink-600)" }}>Pending invites</span></span>
            <span style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 8, ...mono }}><I.Clock size={15} /> Active since 2/14/2026</span>
          </Inset>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {members.map(([name, email, role, status], i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, background: "var(--paper-50)", border: "1px solid var(--border)", borderRadius: "var(--radius-md)", padding: "12px 16px" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 14, minWidth: 0 }}>
                  <span style={{ width: 34, height: 34, flex: "none", borderRadius: "50%", background: "var(--oxblood-100)", color: "var(--oxblood-600)", display: "flex", alignItems: "center", justifyContent: "center", font: "600 13px/1 var(--font-display)", letterSpacing: "0.04em" }}>
                    {name.split(" ").map((w) => w[0]).join("")}
                  </span>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ font: "600 14px/1.2 var(--font-sans)", color: "var(--ink-900)" }}>{name}</div>
                    <div style={{ font: "400 12.5px/1 var(--font-sans)", color: "var(--ink-500)", marginTop: 3 }}>{email}</div>
                  </div>
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 10, flex: "none" }}>
                  <Badge tone="neutral">{role}</Badge>
                  <Badge tone="success" dot>{status}</Badge>
                </div>
              </div>
            ))}
          </div>

          <div style={{ font: "600 13.5px/1 var(--font-sans)", color: "var(--ink-900)", margin: "22px 0 12px" }}>Pending invites</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {invites.map(([email, role, when], i) => (
              <Inset key={i} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, padding: "12px 16px" }}>
                <div style={{ minWidth: 0 }}>
                  <div style={{ font: "500 14px/1.2 var(--font-sans)", color: "var(--ink-900)" }}>{email}</div>
                  <div style={{ ...mono, marginTop: 4 }}>{role} · {when}</div>
                </div>
                <div style={{ display: "flex", gap: 8, flex: "none" }}>
                  <Button variant="outline" size="sm" icon={<I.Copy size={14} />}>Resend</Button>
                  <Button variant="ghost" size="sm" icon={<I.Trash size={14} />}>Revoke</Button>
                </div>
              </Inset>
            ))}
          </div>
          <div style={{ marginTop: 14 }}>
            <Field label="Invite by email" placeholder="teammate@example.com" right={<Button variant="default" size="sm" icon={<I.Plus size={15} />}>Send invite</Button>} hint="Sends them your team's public key and a starter pack. They import it locally — no account is created and nothing is uploaded." />
          </div>
        </Section>

        {/* EXPORT */}
        <Section icon={I.Download} title="Export a pack" desc="Bundle your local memory into a .rokkorpack. Sign it with a team key so importers can verify the author." action={<Button variant="outline" size="sm" icon={<I.Refresh size={15} />}>Refresh counts</Button>}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 18 }}>
            {[["Vocabulary", "vocab", counts.vocab], ["Snippets", "snippets", counts.snippets], ["Corrections", "corrections", counts.corrections], ["Transforms", "transforms", counts.transforms]].map(([label, key, n]) => (
              <div key={key} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, background: "var(--paper-50)", border: "1px solid var(--border)", borderRadius: "var(--radius-md)", padding: "13px 16px" }}>
                <div style={{ font: "400 14px/1 var(--font-sans)" }}>
                  <span style={{ fontWeight: 600, color: "var(--ink-900)" }}>{label}</span>
                  <span style={{ marginLeft: 8, color: "var(--ink-500)" }}>({n.toLocaleString()})</span>
                </div>
                <Switch checked={payloads[key]} onCheckedChange={togglePayload(key)} />
              </div>
            ))}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 14 }}>
            <Field label="Title" value="Platform Team Pack" />
            <Field label="Author (optional)" value="Platform Team" />
          </div>
          <Field label="Signing key (optional, base64 secret key)" placeholder="Paste a team secret key to sign — leave blank for an unsigned pack" mono hint="Sign so importers can verify the author against your pinned public key. ROKKOR never stores the secret key." />
          <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 18 }}>
            <Button variant="default" icon={<I.Download size={15} />}>Export .rokkorpack</Button>
          </div>
        </Section>

        {/* IMPORT */}
        <Section icon={I.Folder} title="Import a pack" desc="Apply a teammate's .rokkorpack or migrate a competitor vocabulary CSV. Choose how to resolve collisions, and optionally require a verified signature.">
          <div style={{ display: "flex", flexWrap: "wrap", alignItems: "flex-end", gap: 16 }}>
            <Select label="On conflict" value="Keep both (rename)" options={["Skip", "Overwrite", "Keep both (rename)"]} style={{ width: 220 }} />
            <label style={{ display: "flex", alignItems: "center", gap: 10, font: "400 14px/1 var(--font-sans)", color: "var(--ink-900)", paddingBottom: 12 }}>
              <Switch checked={true} onCheckedChange={() => {}} /> Require verified signature
            </label>
            <div style={{ paddingBottom: 4 }}><Button variant="outline" size="sm" icon={<I.Folder size={15} />}>Choose file…</Button></div>
          </div>

          <Field label="Team public key to pin (optional, base64)" value={pubKey} mono hint="Without a pinned key a valid signature only proves the pack is internally consistent (self-signed) — it does NOT prove who authored it." style={{ marginTop: 16 }} />

          {/* Preview of a selected pack */}
          <Inset style={{ marginTop: 16 }}>
            <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 16 }}>
              <div style={{ minWidth: 0 }}>
                <div style={{ font: "600 14px/1.3 var(--font-mono)", color: "var(--ink-900)", wordBreak: "break-all" }}>platform-vocab-2026-06.rokkorpack</div>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 8, font: "400 13px/1 var(--font-sans)", color: "var(--ink-500)" }}>
                  Author: Maya Renner <Badge tone="success" dot>verified author</Badge>
                </div>
              </div>
              <div style={{ flex: "none" }}><Button variant="default" size="sm" icon={<I.Check size={15} />}>Import</Button></div>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginTop: 16 }}>
              {[["Vocabulary", 281], ["Snippets", 0], ["Corrections", 0], ["Transforms", 0]].map(([l, v]) => (
                <div key={l} style={{ border: "1px solid var(--border)", borderRadius: "var(--radius-md)", padding: "10px 12px", background: "var(--card)" }}>
                  <div style={{ font: "600 11px/1 var(--font-display)", letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ink-500)" }}>{l}</div>
                  <div style={{ font: "600 17px/1 var(--font-serif)", color: "var(--ink-900)", marginTop: 6 }}>{v}</div>
                </div>
              ))}
            </div>
          </Inset>

          <div style={{ font: "600 13.5px/1 var(--font-sans)", color: "var(--ink-900)", margin: "22px 0 12px" }}>Recently imported</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {recentPacks.map(([file, author, when, status, n], i) => {
              const verified = status === "verified author";
              return (
                <Inset key={i} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, padding: "12px 16px" }}>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ font: "500 13.5px/1.3 var(--font-mono)", color: "var(--ink-900)", wordBreak: "break-all" }}>{file}</div>
                    <div style={{ ...mono, marginTop: 5 }}>{author} · {when} · {n} items</div>
                  </div>
                  <Badge tone={verified ? "success" : "neutral"} dot={verified}>{status}</Badge>
                </Inset>
              );
            })}
          </div>
        </Section>

        {/* SIGNING KEY */}
        <Section icon={I.Lock} title="Team signing key" desc="An ed25519 keypair signs packs (authenticity only — no PKI). Keep the secret key to sign; share the public key with importers so they can verify the author. ROKKOR never stores the secret key.">
          <Inset style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 14 }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ font: "600 11px/1 var(--font-display)", letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ink-500)" }}>Public key</div>
              <div style={{ font: "13px/1.4 var(--font-mono)", color: "var(--ink-900)", marginTop: 6, wordBreak: "break-all" }}>{pubKey}</div>
            </div>
            <Button variant="ghost" size="sm" icon={<I.Copy size={15} />}>Copy</Button>
          </Inset>
          <Inset style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 14, marginTop: 12 }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ font: "600 11px/1 var(--font-display)", letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ink-500)" }}>
                Secret key <span style={{ color: "var(--oxblood-600)", marginLeft: 8 }}>keep private</span>
              </div>
              <div style={{ font: "13px/1.4 var(--font-mono)", color: "var(--ink-900)", marginTop: 6, letterSpacing: "0.1em" }}>•••• •••• •••• •••• •••• •••• ••••</div>
            </div>
            <Button variant="ghost" size="sm" icon={<I.Copy size={15} />}>Reveal</Button>
          </Inset>
          <Notice tone="warning" style={{ marginTop: 14 }}>
            The secret key is held only in this session and is never written to disk by ROKKOR. Store it in your password manager — if you lose it you can no longer sign as this team, and you will need to rotate to a new key and re-pin it everywhere.
          </Notice>
          <div style={{ display: "flex", gap: 10, marginTop: 16 }}>
            <Button variant="outline" icon={<I.Refresh size={15} />}>Generate new keypair</Button>
            <Button variant="ghost" icon={<I.Download size={15} />}>Export public key</Button>
          </div>
        </Section>

        {/* LOCAL API SERVER */}
        <Section icon={I.Cloud} title="Local API server" desc="Expose ROKKOR's transcribe + clean core to OTHER local apps over a loopback (127.0.0.1) HTTP server. Off by default. Every request needs the bearer token below, so a co-resident process cannot use it silently. Nothing is exposed to the network.">
          <Inset style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16 }}>
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 10, font: "600 14px/1 var(--font-sans)", color: "var(--ink-900)" }}>
                {server ? "Running" : "Stopped"}
                <span style={{ ...mono, color: "var(--ink-500)" }}>http://127.0.0.1:8787</span>
              </div>
              {server ? <div style={{ font: "400 12.5px/1.4 var(--font-sans)", color: "var(--success-600)", marginTop: 6 }}>Listening on loopback only · 1,084 requests served this month</div> : null}
            </div>
            <Switch checked={server} onCheckedChange={setServer} />
          </Inset>
          <Inset style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 14, marginTop: 12 }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ font: "600 11px/1 var(--font-display)", letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ink-500)" }}>
                Bearer token <span style={{ color: "var(--oxblood-600)", marginLeft: 8 }}>keep private</span>
              </div>
              <div style={{ font: "13px/1.4 var(--font-mono)", color: "var(--ink-900)", marginTop: 6, wordBreak: "break-all" }}>rk_live_4e99ef_a7Qp2-Lk9sVt3xR8mB1nC6dW</div>
            </div>
            <div style={{ display: "flex", gap: 6, flex: "none" }}>
              <Button variant="ghost" size="sm" icon={<I.Copy size={15} />}>Copy</Button>
              <Button variant="ghost" size="sm" icon={<I.Refresh size={15} />}>Rotate</Button>
            </div>
          </Inset>
          <Notice tone="info" style={{ marginTop: 14 }}>
            Bound to 127.0.0.1 — only apps already on this machine can reach it, and only with the bearer token above. It is never advertised on your LAN. Rotate the token any time to revoke every existing integration at once.
          </Notice>
        </Section>
      </div>
    </div>
  );
}

window.RokkorScreens = Object.assign(window.RokkorScreens || {}, { TeamsScreen });
