// Pricing, Promos, Campaigns, Flags, Themes, Audit, Settings

function PagePricing() {
  return (
    <>
      <div className="page-header"><div><h1>Pricing & Packs</h1><div className="sub">Changes propagate to iOS, Android, and web in ~10 minutes.</div></div>
      <div className="actions"><button className="btn primary sm"><Icon.plus size={12}/> New plan</button></div>
      </div>

      <h3 style={{fontSize:13, marginBottom:10}}>Subscription plans</h3>
      <div style={{display:"grid", gridTemplateColumns:"repeat(auto-fit, minmax(220px,1fr))", gap:14, marginBottom:24}}>
        {PLANS.map(p=>(
          <div key={p.id} className="card" style={{padding:0}}>
            <div className="card-body">
              <div className="hstack">
                <div style={{fontFamily:"var(--display)", fontWeight:600, fontSize:15}}>{p.name}</div>
                <div className="spacer"/>
                <Switch on={p.id!=="free"} onChange={()=>{}}/>
              </div>
              <div style={{fontFamily:"var(--display)", fontSize:28, fontWeight:600, marginTop:6}}>
                {p.price === 0 ? "Free" : money(p.price)}
                {p.price > 0 && <span style={{fontSize:13, color:"var(--ink-3)"}}> /mo</span>}
              </div>
              <div className="muted" style={{fontSize:12, marginTop:6}}>
                {p.id==="free" ? "3 welcome credits · ads" :
                 p.id==="starter" ? "15 stories/mo · no ads" :
                 p.id==="family" ? "50 stories/mo · 2 kids" :
                 "Unlimited · premium voices · 4 kids"}
              </div>
              <div className="bar" style={{marginTop:14}}><span style={{width:Math.min(100, PLAN_DIST.find(x=>x.plan===p.name)?.users/KPIS.users*100||0)+"%", background:p.color}}/></div>
              <div className="hstack" style={{marginTop:6, fontSize:11}}>
                <span className="muted">{(PLAN_DIST.find(x=>x.plan===p.name)?.users || 0).toLocaleString()} users</span>
                <div className="spacer"/>
                <span className="mono">{money((PLAN_DIST.find(x=>x.plan===p.name)?.revenue) || 0)} MRR</span>
              </div>
              <div className="hstack" style={{marginTop:12}}>
                <button className="btn sm" style={{width:"100%", justifyContent:"center"}}>Edit</button>
              </div>
            </div>
          </div>
        ))}
      </div>

      <h3 style={{fontSize:13, marginBottom:10}}>Credit packs (one-time)</h3>
      <div className="card">
        <div className="table-wrap">
          <table className="tbl">
            <thead><tr><th>Pack</th><th style={{textAlign:"right"}}>Credits</th><th style={{textAlign:"right"}}>Price</th><th style={{textAlign:"right"}}>$/credit</th><th>iOS SKU</th><th>Android SKU</th><th>Status</th><th></th></tr></thead>
            <tbody>
              {CREDIT_PACKS.map(p=>(
                <tr key={p.id}>
                  <td><b>{p.name}</b> {p.popular && <span className="badge accent" style={{marginLeft:6}}>Popular</span>}</td>
                  <td className="num">{p.credits}</td>
                  <td className="num">{money(p.price)}</td>
                  <td className="num muted">{money(p.price/p.credits)}</td>
                  <td className="muted mono">com.talio.{p.id}</td>
                  <td className="muted mono">pack_{p.id}</td>
                  <td><span className="badge green"><Icon.check size={10}/> Live</span></td>
                  <td><button className="btn ghost icon sm"><Icon.more size={14}/></button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
}

function PagePromos() {
  return (
    <>
      <div className="page-header"><div><h1>Promos & Gifts</h1><div className="sub">Discount codes, free credits, and influencer grants.</div></div>
      <div className="actions"><button className="btn primary sm"><Icon.plus size={12}/> New code</button></div></div>

      <div className="kpi-grid">
        <KPI label="Active codes"          value={String(PROMOS.filter(p=>p.active).length) || "0"}/>
        <KPI label="Redemptions (30d)"     value="—" delta={null}/>
        <KPI label="Attributable revenue"  value="—" delta={null}/>
        <KPI label="Gift credits issued"   value="—" delta={null}/>
      </div>

      <div className="card">
        <div className="table-wrap">
          <table className="tbl">
            <thead><tr><th>Code</th><th>Type</th><th>Value</th><th style={{textAlign:"right"}}>Redeemed</th><th>Expires</th><th>Status</th><th></th></tr></thead>
            <tbody>
              {PROMOS.length === 0 && <tr><td colSpan={7}><EmptyState icon="star" message="No promo codes yet" sub="Create your first promo code to get started"/></td></tr>}
              {PROMOS.map(p=>(
                <tr key={p.code}>
                  <td><span className="mono" style={{fontWeight:600, background:"var(--bg-soft)", padding:"2px 6px", borderRadius:4, border:"1px solid var(--border)"}}>{p.code}</span></td>
                  <td>{p.type}</td>
                  <td>{p.value}</td>
                  <td className="num">{p.redeemed.toLocaleString()} {p.limit && <span className="muted">/ {p.limit.toLocaleString()}</span>}</td>
                  <td className="muted">{p.expires}</td>
                  <td>{p.active ? <span className="badge green">Active</span> : <span className="badge">Expired</span>}</td>
                  <td><button className="btn ghost icon sm"><Icon.more size={14}/></button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
}

function PageCampaigns() {
  const campaigns = [];
  return (
    <>
      <div className="page-header"><div><h1>Campaigns</h1><div className="sub">Push, email, and in-app messages to users.</div></div>
      <div className="actions"><button className="btn primary sm"><Icon.plus size={12}/> New campaign</button></div></div>

      <div className="kpi-grid">
        <KPI label="Active campaigns" value={String(campaigns.filter(c=>c.status==="active").length) || "0"}/>
        <KPI label="Sent (7d)"        value="—"/>
        <KPI label="Avg open rate"    value="—" unit="" delta={null}/>
        <KPI label="Avg conversion"   value="—" unit="" delta={null}/>
      </div>

      <div className="card">
        <div className="table-wrap">
          <table className="tbl">
            <thead><tr><th>Campaign</th><th>Audience</th><th>Channel</th><th style={{textAlign:"right"}}>Sent</th><th>Open</th><th>Conv</th><th>Status</th><th></th></tr></thead>
            <tbody>
              {campaigns.map(c=>(
                <tr key={c.name}>
                  <td><b>{c.name}</b></td>
                  <td className="muted">{c.audience}</td>
                  <td>{c.channel}</td>
                  <td className="num">{c.sent.toLocaleString()}</td>
                  <td className="mono">{c.opened}</td>
                  <td className="mono" style={{color: parseFloat(c.converted)>10?"var(--green)":undefined}}>{c.converted}</td>
                  <td>{c.status==="active" ? <span className="badge green"><span className="pulse"/> Active</span> :
                      c.status==="scheduled" ? <span className="badge blue">Scheduled</span> :
                      <span className="badge amber">Paused</span>}</td>
                  <td><button className="btn ghost icon sm"><Icon.more size={14}/></button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
}

function PageFlags() {
  const [flags, setFlags] = React.useState(FLAGS);
  return (
    <>
      <div className="page-header"><div><h1>Feature flags</h1><div className="sub">Toggle features per env. Changes take effect in ~30s.</div></div>
      <div className="actions"><button className="btn primary sm"><Icon.plus size={12}/> New flag</button></div></div>
      <div className="card">
        <div className="table-wrap">
          <table className="tbl">
            <thead><tr><th>Flag</th><th>Key</th><th>Env</th><th>Rollout</th><th>Status</th><th></th></tr></thead>
            <tbody>
              {flags.map((f,i)=>(
                <tr key={f.key}>
                  <td><b>{f.name}</b></td>
                  <td className="mono muted">{f.key}</td>
                  <td><span className={"badge "+(f.env==="prod"?"green":f.env==="staging"?"amber":"blue")}>{f.env}</span></td>
                  <td style={{width:200}}>
                    <div className="hstack">
                      <div className="bar" style={{flex:1, maxWidth:120}}><span style={{width:f.rollout+"%"}}/></div>
                      <span className="mono" style={{fontSize:11, minWidth:30, textAlign:"right"}}>{f.rollout}%</span>
                    </div>
                  </td>
                  <td><Switch on={f.enabled} onChange={v=>{const nf=[...flags]; nf[i]={...f, enabled:v}; setFlags(nf);}}/></td>
                  <td><button className="btn ghost icon sm"><Icon.more size={14}/></button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
}

const PROMPT_AGE_GROUPS = ["1-2", "2-3", "3-4", "4-5", "5-6", "6+"];

function PromptDrawer({ open, onClose }) {
  const [loading, setLoading]   = React.useState(false);
  const [saving, setSaving]     = React.useState(false);
  const [savedAt, setSavedAt]   = React.useState(null);
  const [error, setError]       = React.useState(null);
  const [config, setConfig]     = React.useState(null);
  const [draft, setDraft]       = React.useState(null);

  React.useEffect(() => { if (open) load(); }, [open]);

  async function load() {
    setLoading(true); setError(null);
    try {
      const res  = await window.__adminGetPromptConfig({});
      const data = res.data || { systemPromptTemplate: "", ageGuidelines: {} };
      setConfig(JSON.parse(JSON.stringify(data)));
      setDraft(JSON.parse(JSON.stringify(data)));
    } catch(e) { setError(e.message || "Failed to load"); }
    finally { setLoading(false); }
  }

  async function save() {
    setSaving(true); setError(null);
    try {
      await window.__adminSetPromptConfig(draft);
      setConfig(JSON.parse(JSON.stringify(draft)));
      setSavedAt(new Date());
    } catch(e) { setError(e.message || "Failed to save"); }
    finally { setSaving(false); }
  }

  const dirty = draft && config && JSON.stringify(config) !== JSON.stringify(draft);

  if (!open) return null;

  return (
    <>
      <div className="drawer-backdrop" onClick={onClose}/>
      <div className="drawer" style={{width:680, maxWidth:"92vw", display:"flex", flexDirection:"column"}}>
        {/* Header */}
        <header style={{flexShrink:0}}>
          <div style={{fontWeight:600}}>Prompt Configuration</div>
          <div className="spacer"/>
          {savedAt && !dirty && <span className="badge green" style={{marginRight:8}}><Icon.check size={10}/> Saved {savedAt.toLocaleTimeString()}</span>}
          {dirty   && <span className="badge amber" style={{marginRight:8}}>Unsaved changes</span>}
          <button className="btn ghost icon sm" onClick={load} disabled={loading||saving} title="Reload from Firestore" style={{marginRight:4}}>
            <Icon.rotate size={13}/>
          </button>
          <button className="btn primary sm" onClick={save} disabled={saving||loading||!dirty} style={{marginRight:8}}>
            {saving ? "Saving…" : <><Icon.check size={12}/> Save</>}
          </button>
          <button className="btn ghost icon sm" onClick={onClose}><Icon.close size={14}/></button>
        </header>

        {/* Body */}
        <div className="body" style={{flex:1, overflowY:"auto", padding:"20px 24px"}}>
          {error && (
            <div style={{background:"var(--bg-soft)", border:"1px solid var(--border)", borderRadius:8, padding:"10px 14px", marginBottom:16, color:"var(--red,#c00)", fontSize:12}}>
              {error}
            </div>
          )}

          {loading && (
            <div style={{display:"flex", alignItems:"center", gap:10, padding:"48px 0", justifyContent:"center", color:"var(--ink-4)"}}>
              <Icon.rotate size={16} style={{animation:"spin 1s linear infinite"}}/>
              <span style={{fontSize:13}}>Loading from Firestore…</span>
            </div>
          )}

          {!loading && draft && (<>
            {/* System prompt */}
            <div style={{marginBottom:24}}>
              <div style={{fontWeight:600, fontSize:13, marginBottom:4}}>System Prompt Template</div>
              <div style={{fontSize:11, color:"var(--ink-4)", marginBottom:8}}>
                Runtime tokens:&nbsp;
                <code style={{fontFamily:"var(--mono)", color:"var(--accent)", fontSize:11}}>{"{{WORDS_PER_PAGE}}"}</code>
                &nbsp;·&nbsp;
                <code style={{fontFamily:"var(--mono)", color:"var(--accent)", fontSize:11}}>{"{{VOCAB_GUIDELINES}}"}</code>
                &nbsp;— replaced per age group. Changes propagate in ~5 min.
              </div>
              <textarea
                value={draft.systemPromptTemplate}
                onChange={e => setDraft(d => ({...d, systemPromptTemplate: e.target.value}))}
                spellCheck={false}
                style={{
                  width:"100%", minHeight:300, padding:"12px 14px", borderRadius:8,
                  border:"1px solid var(--border)", background:"var(--bg-elev)", color:"var(--ink)",
                  fontFamily:"var(--mono)", fontSize:12, lineHeight:1.65,
                  resize:"vertical", boxSizing:"border-box", outline:"none",
                }}
              />
              <div style={{marginTop:5, fontSize:11, color:"var(--ink-4)", textAlign:"right"}}>
                {draft.systemPromptTemplate.length.toLocaleString()} chars
                &nbsp;·&nbsp;{draft.systemPromptTemplate.trim().split(/\s+/).filter(Boolean).length.toLocaleString()} words
              </div>
            </div>

            {/* Age guidelines */}
            <div>
              <div style={{fontWeight:600, fontSize:13, marginBottom:10}}>Age Guidelines</div>
              <table className="tbl" style={{width:"100%"}}>
                <thead>
                  <tr>
                    <th style={{width:60}}>Age</th>
                    <th>Words / page <span className="muted" style={{fontWeight:400, fontSize:11}}>(→ WORDS_PER_PAGE)</span></th>
                    <th>Vocabulary style <span className="muted" style={{fontWeight:400, fontSize:11}}>(→ VOCAB_GUIDELINES)</span></th>
                  </tr>
                </thead>
                <tbody>
                  {PROMPT_AGE_GROUPS.map(age => {
                    const g = (draft.ageGuidelines && draft.ageGuidelines[age]) || {words:"", vocab:""};
                    return (
                      <tr key={age}>
                        <td>
                          <span style={{display:"inline-flex", alignItems:"center", justifyContent:"center", width:38, height:20, borderRadius:5, background:"var(--accent)", color:"white", fontWeight:600, fontSize:11}}>{age}</span>
                        </td>
                        <td style={{padding:"6px 12px"}}>
                          <input value={g.words}
                            onChange={e => setDraft(d => ({...d, ageGuidelines:{...d.ageGuidelines, [age]:{...g, words:e.target.value}}}))}
                            style={{width:"100%", padding:"5px 9px", borderRadius:5, border:"1px solid var(--border)", background:"var(--bg-elev)", color:"var(--ink)", fontFamily:"var(--mono)", fontSize:12, boxSizing:"border-box"}}
                          />
                        </td>
                        <td style={{padding:"6px 12px"}}>
                          <input value={g.vocab}
                            onChange={e => setDraft(d => ({...d, ageGuidelines:{...d.ageGuidelines, [age]:{...g, vocab:e.target.value}}}))}
                            style={{width:"100%", padding:"5px 9px", borderRadius:5, border:"1px solid var(--border)", background:"var(--bg-elev)", color:"var(--ink)", fontSize:12, boxSizing:"border-box"}}
                          />
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </>)}
        </div>

        {/* Sticky footer when dirty */}
        {dirty && (
          <footer style={{flexShrink:0, padding:"12px 24px", borderTop:"1px solid var(--border)", display:"flex", gap:8, alignItems:"center"}}>
            <span style={{fontSize:12, color:"var(--ink-3)", flex:1}}>You have unsaved changes.</span>
            <button className="btn sm" onClick={() => setDraft(JSON.parse(JSON.stringify(config)))} disabled={saving}>Discard</button>
            <button className="btn primary sm" onClick={save} disabled={saving}>{saving ? "Saving…" : "Save changes"}</button>
          </footer>
        )}
      </div>
    </>
  );
}

function PageThemes() {
  const [drawerOpen, setDrawerOpen] = React.useState(false);
  return (
    <>
      <PromptDrawer open={drawerOpen} onClose={() => setDrawerOpen(false)}/>
      <div className="page-header">
        <div><h1>Themes & Story prompts</h1><div className="sub">The building blocks kids pick from in the app. Story counts are live from Firestore.</div></div>
        <div className="actions">
          <button className="btn primary sm" onClick={() => setDrawerOpen(true)}><Icon.sparkle size={12}/> Edit prompts</button>
        </div>
      </div>
      <div style={{display:"grid", gridTemplateColumns:"repeat(auto-fill, minmax(220px,1fr))", gap:14}}>
        {THEMES.map((t,i)=>{
          const hue = (i * 55) % 360;
          const stories = THEME_DIST.find(d=>d.theme===t)?.stories || 0;
          return (
            <div key={t} className="card">
              <div className="card-body">
                <div className="hstack">
                  <div style={{width:40, height:40, borderRadius:10, background:`linear-gradient(135deg, hsl(${hue},65%,62%), hsl(${(hue+60)%360},60%,45%))`, display:"grid", placeItems:"center", color:"white"}}>
                    <Icon.sparkle size={18}/>
                  </div>
                  <div className="spacer"/>
                  <Switch on={true} onChange={()=>{}}/>
                </div>
                <div style={{fontFamily:"var(--display)", fontWeight:600, fontSize:14, marginTop:10}}>{t}</div>
                <div className="muted" style={{fontSize:12, marginTop:2}}>{stories > 0 ? `${compact(stories)} stories` : "No stories yet"}</div>
                <div className="hstack" style={{marginTop:10}}>
                  <button className="btn sm" style={{flex:1, justifyContent:"center"}} onClick={() => setDrawerOpen(true)}>Edit prompts</button>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </>
  );
}

function PageAudit() {
  const [search, setSearch] = React.useState("");
  const [days,   setDays]   = React.useState("all");

  const log = window.AUDIT_LOG || [];

  const cutoff = days === "all" ? null : new Date(Date.now() - Number(days) * 86400000);

  const filtered = log.filter(e => {
    if (cutoff && e.timestamp && new Date(e.timestamp) < cutoff) return false;
    if (search) {
      const q = search.toLowerCase();
      const hay = [e.action, e.adminEmail, e.target, e.details].join(" ").toLowerCase();
      if (!hay.includes(q)) return false;
    }
    return true;
  });

  function exportCSV() {
    const rows = [["When","Admin","Action","Target","Details"]];
    filtered.forEach(e => rows.push([e.timestamp||"", e.adminEmail||"", e.action||"", e.target||"", e.details||""]));
    const csv = rows.map(r => r.map(c => `"${String(c).replace(/"/g,'""')}"`).join(",")).join("\n");
    const a = document.createElement("a");
    a.href = "data:text/csv;charset=utf-8," + encodeURIComponent(csv);
    a.download = `audit-log-${new Date().toISOString().slice(0,10)}.csv`;
    a.click();
  }

  return (
    <>
      <div className="page-header">
        <div><h1>Audit log</h1><div className="sub">Every admin action is recorded automatically.</div></div>
        <div className="actions">
          <button className="btn sm" onClick={exportCSV}><Icon.download size={12}/> Export CSV</button>
        </div>
      </div>
      <div className="card">
        <div className="toolbar">
          <div className="input search" style={{flex:1, maxWidth:340}}>
            <Icon.search size={13}/>
            <input placeholder="Search action, admin, target…" value={search} onChange={e=>setSearch(e.target.value)}/>
          </div>
          <div className="input">
            <span className="muted">Last:</span>
            <select value={days} onChange={e=>setDays(e.target.value)}>
              <option value="all">All time</option>
              <option value="1">24 hours</option>
              <option value="7">7 days</option>
              <option value="30">30 days</option>
              <option value="90">90 days</option>
            </select>
          </div>
        </div>
        <div className="table-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th>When</th>
                <th>Admin</th>
                <th>Action</th>
                <th>Target</th>
              </tr>
            </thead>
            <tbody>
              {filtered.length === 0 && (
                <tr><td colSpan={4}>
                  <EmptyState icon="log" message="No audit events yet"
                    sub="Admin actions like saving prompt config will appear here automatically"/>
                </td></tr>
              )}
              {filtered.map(e => {
                const initials = (e.adminEmail || "?").split(/[@.]/).filter(Boolean).map(s=>s[0]).slice(0,2).join("").toUpperCase();
                return (
                  <tr key={e.id}>
                    <td className="muted" style={{whiteSpace:"nowrap"}}>{fmtRelative(e.timestamp)}</td>
                    <td>
                      <div className="hstack">
                        <div className="avatar" style={{width:22, height:22, fontSize:9}}>{initials}</div>
                        <span style={{fontSize:12}}>{e.adminEmail || "Unknown"}</span>
                      </div>
                    </td>
                    <td style={{fontWeight:500}}>{e.action}</td>
                    <td className="muted mono" style={{fontSize:11}}>{e.target || "—"}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          {filtered.length > 0 && (
            <div style={{padding:"10px 14px", fontSize:12, color:"var(--ink-3)", borderTop:"1px solid var(--border)"}}>
              {filtered.length} event{filtered.length !== 1 ? "s" : ""}
            </div>
          )}
        </div>
      </div>
    </>
  );
}

const ADMIN_TEAM = [
  { name: "Adi Goldstein", email: "adi@talio.fun",       role: "super",  initials: "AG" },
  { name: "Elad",          email: "elad@corefix.tech",   role: "admin",  initials: "EL" },
  { name: "Almog",         email: "almog@corefix.tech",  role: "admin",  initials: "AL" },
  { name: "Kobi",          email: "kobi@corfix.tech",    role: "admin",  initials: "KO" },
  { name: "Rave",          email: "rave@altfred.com",    role: "admin",  initials: "RA" },
];

function AdminRowMenu({ admin, currentEmail }) {
  const [open, setOpen] = React.useState(false);
  const [copied, setCopied] = React.useState(false);
  const ref = React.useRef();
  const isSelf = admin.email === currentEmail;

  React.useEffect(() => {
    if (!open) return;
    const onClick = e => { if (!ref.current?.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", onClick);
    return () => document.removeEventListener("mousedown", onClick);
  }, [open]);

  function copyEmail() {
    navigator.clipboard?.writeText(admin.email).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 1800);
    });
    setOpen(false);
  }

  const menuItemStyle = (disabled, danger) => ({
    display:"flex", alignItems:"center", gap:9, width:"100%",
    padding:"8px 12px", background:"none", border:"none",
    cursor: disabled ? "not-allowed" : "pointer", fontSize:13,
    color: disabled ? "var(--ink-4)" : danger ? "var(--red,#e53e3e)" : "var(--ink)",
    borderRadius:6, textAlign:"left", opacity: disabled ? 0.55 : 1,
  });

  return (
    <div ref={ref} style={{position:"relative", display:"inline-block"}}>
      {copied && (
        <span style={{position:"absolute", right:32, top:"50%", transform:"translateY(-50%)", fontSize:11, color:"var(--green,#22c55e)", whiteSpace:"nowrap", pointerEvents:"none"}}>
          Copied!
        </span>
      )}
      <button className="btn ghost icon sm" onClick={() => setOpen(o => !o)} title="Admin actions">
        <Icon.more size={14}/>
      </button>
      {open && (
        <div style={{
          position:"absolute", right:0, top:"calc(100% + 4px)", zIndex:300,
          background:"var(--bg-elev)", border:"1px solid var(--border)", borderRadius:10,
          boxShadow:"0 8px 28px rgba(0,0,0,.15)", minWidth:190, padding:4,
        }}>
          <button style={menuItemStyle(false, false)} onClick={copyEmail}>
            <Icon.mail size={13}/> Copy email
          </button>
          <button style={menuItemStyle(isSelf || admin.role==="super", false)} disabled={isSelf || admin.role==="super"} onClick={() => setOpen(false)}>
            <Icon.users size={13}/> Change role
          </button>
          <button style={menuItemStyle(isSelf, false)} disabled={isSelf} onClick={() => setOpen(false)}>
            <Icon.lock size={13}/> Reset password
          </button>
          <div style={{height:1, background:"var(--border)", margin:"4px 0"}}/>
          <button style={menuItemStyle(isSelf, !isSelf)} disabled={isSelf} onClick={() => setOpen(false)}>
            <Icon.trash size={13}/> Remove admin
          </button>
        </div>
      )}
    </div>
  );
}

function IntegrationsCard() {
  const integrations = [
    { name:"OpenAI",      desc:"GPT-4o story generation + TTS narration", connected:true,  color:"hsl(145,55%,45%)" },
    { name:"Replicate",   desc:"Flux Schnell AI illustration generation",  connected:true,  color:"hsl(145,55%,45%)" },
    { name:"Resend",      desc:"Transactional email delivery",             connected:true,  color:"hsl(145,55%,45%)" },
    { name:"Firebase",    desc:"Auth, Firestore, Cloud Storage, Functions",connected:true,  color:"hsl(145,55%,45%)" },
    { name:"Stripe",      desc:"Subscription billing & web payments",      connected:false, color:null },
    { name:"Apple IAP",   desc:"App Store in-app purchases",               connected:false, color:null },
    { name:"Google Play", desc:"Play Store in-app purchases",              connected:false, color:null },
    { name:"RevenueCat",  desc:"Cross-platform subscription management",   connected:false, color:null },
    { name:"Sentry",      desc:"Error monitoring & crash reporting",       connected:false, color:null },
  ];
  const connectedCount = integrations.filter(i => i.connected).length;
  const notCount = integrations.length - connectedCount;

  return (
    <div className="card">
      <div className="card-header">
        <h3>Integrations</h3>
        <div className="spacer"/>
        <span style={{fontSize:11, color:"var(--ink-4)"}}>
          <span style={{color:"var(--green,#22c55e)", fontWeight:600}}>{connectedCount} connected</span>
          {" · "}{notCount} not connected
        </span>
      </div>
      <div>
        {integrations.map((intg, i) => (
          <div key={intg.name} style={{
            padding:"14px 20px", display:"flex", alignItems:"center", gap:14,
            borderBottom: i < integrations.length - 1 ? "1px solid var(--border)" : undefined,
          }}>
            <div style={{
              width:38, height:38, borderRadius:10, flexShrink:0,
              display:"grid", placeItems:"center",
              background: intg.connected ? "color-mix(in srgb, hsl(145,55%,45%) 12%, transparent)" : "var(--bg-soft)",
              color: intg.connected ? "hsl(145,55%,38%)" : "var(--ink-4)",
              fontSize:15, fontWeight:700, fontFamily:"var(--mono)",
            }}>
              {intg.connected ? <Icon.check size={17}/> : <Icon.close size={15}/>}
            </div>
            <div style={{flex:1, minWidth:0}}>
              <div style={{fontWeight:600, fontSize:13}}>{intg.name}</div>
              <div style={{fontSize:11, color:"var(--ink-4)", marginTop:1}}>{intg.desc}</div>
            </div>
            {intg.connected
              ? <span className="badge green" style={{flexShrink:0}}><Icon.check size={10}/> Connected</span>
              : <button className="btn sm" style={{flexShrink:0}}>Set up</button>
            }
          </div>
        ))}
      </div>
    </div>
  );
}

function PageSettings() {
  const currentEmail = window.__auth?.currentUser?.email;
  return (
    <>
      <div className="page-header"><div><h1>Settings</h1><div className="sub">Admin accounts, API keys, and workspace config.</div></div></div>

      <div className="card" style={{marginBottom:20}}>
        <div className="card-header"><h3>Admins</h3><div className="spacer"/>
          <span style={{fontSize:11, color:"var(--ink-4)"}}>Password for all accounts: Talio123!</span>
        </div>
        <div className="table-wrap">
          <table className="tbl">
            <thead><tr><th>Admin</th><th>Email</th><th>Role</th><th></th></tr></thead>
            <tbody>
              {ADMIN_TEAM.map(a=>(
                <tr key={a.email} style={{background: a.email===currentEmail ? "var(--accent-soft)" : undefined}}>
                  <td>
                    <div className="hstack">
                      <div className="avatar" style={{width:28, height:28, fontSize:11}}>{a.initials}</div>
                      <b>{a.name}</b>
                      {a.email===currentEmail && <span className="badge accent" style={{marginLeft:4}}>You</span>}
                    </div>
                  </td>
                  <td className="muted">{a.email}</td>
                  <td>{a.role==="super"
                    ? <span className="badge accent">Super admin</span>
                    : <span className="badge">Admin</span>}
                  </td>
                  <td style={{textAlign:"right"}}><AdminRowMenu admin={a} currentEmail={currentEmail}/></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <div className="card" style={{marginBottom:20}}>
        <div className="card-header"><h3>Workspace</h3></div>
        <div className="card-body">
          <div className="settings-row">
            <div><h4>App name</h4><p className="d">Visible to users across the app.</p></div>
            <div><input className="field" defaultValue="Talio" style={{height:34, padding:"0 10px", border:"1px solid var(--border)", borderRadius:7, width:280, background:"var(--bg-elev)", color:"var(--ink)"}}/></div>
          </div>
          <div className="settings-row">
            <div><h4>Welcome credits</h4><p className="d">Given to every new user on signup.</p></div>
            <div><input className="field" defaultValue="3" style={{height:34, padding:"0 10px", border:"1px solid var(--border)", borderRadius:7, width:100, background:"var(--bg-elev)", color:"var(--ink)"}}/></div>
          </div>
          <div className="settings-row">
            <div><h4>Require parent email verification</h4><p className="d">Before purchases are allowed.</p></div>
            <div><Switch on={true} onChange={()=>{}}/></div>
          </div>
          <div className="settings-row">
            <div><h4>COPPA mode</h4><p className="d">Extra safeguards for under-13 users.</p></div>
            <div><Switch on={true} onChange={()=>{}}/></div>
          </div>
          <div className="settings-row">
            <div><h4>Allow story sharing</h4><p className="d">Parents can share finished stories via link.</p></div>
            <div><Switch on={true} onChange={()=>{}}/></div>
          </div>
        </div>
      </div>

      <IntegrationsCard/>
    </>
  );
}

Object.assign(window, { PagePricing, PagePromos, PageCampaigns, PageFlags, PageThemes, PageAudit, PageSettings });
