// CX content screens — Videos, Resources, Education, Support, News

// ─── Video Library (Flow 8) ─────────────────────────────────────────
function VideoLibrary({ go }) {
  const { VIDEOS } = window.MOCK;
  const [cat, setCat] = useState("All");
  const [q, setQ] = useState("");
  const [selected, setSelected] = useState(null);

  const cats = ["All", "Getting Started", "Product Videos", "Webinar Recordings", "Practitioner Spotlights"];
  const filtered = VIDEOS.filter(v =>
    (cat === "All" || v.category === cat) &&
    (q === "" || v.title.toLowerCase().includes(q.toLowerCase()))
  );

  if (selected) {
    const v = VIDEOS.find(x => x.id === selected);
    return (
      <div className="page page-narrow" data-screen-label="08 Video detail">
        <div style={{marginBottom: 18}}>
          <button className="btn sm" onClick={() => setSelected(null)}><I.arrowL size={12}/> Back to library</button>
        </div>
        <div className="card" style={{overflow: "hidden"}}>
          <div style={{background: "linear-gradient(135deg, var(--accent), #5DA399)", height: 360, display: "flex", alignItems: "center", justifyContent: "center", color: "white", position: "relative"}}>
            <div style={{width: 72, height: 72, borderRadius: "50%", background: "rgba(255,255,255,0.2)", display: "grid", placeItems: "center", cursor: "pointer", backdropFilter: "blur(4px)"}}>
              <I.play size={32} style={{marginLeft: 4}}/>
            </div>
            <div style={{position: "absolute", bottom: 16, right: 20, fontSize: 13, opacity: 0.8}} className="mono">{v.duration}</div>
          </div>
          <div className="card-pad" style={{padding: "24px 28px"}}>
            <div className="badge" style={{marginBottom: 10}}>{v.category}</div>
            <h2 style={{fontSize: 22, fontWeight: 700, letterSpacing: "-0.02em", margin: "0 0 6px"}}>{v.title}</h2>
            <div className="muted" style={{fontSize: 13, marginBottom: 16}}>{v.date} · {v.duration}</div>
            <p style={{color: "var(--text-2)", lineHeight: 1.65, margin: 0}}>{v.description}</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="page" data-screen-label="08 Video library">
      <div className="page-head">
        <div>
          <div className="page-title">Video Library</div>
          <div className="page-sub">{VIDEOS.length} videos · Educational content, webinars, and practitioner spotlights</div>
        </div>
        <div className="input-wrap" style={{width: 280}}>
          <I.search className="lead" size={16}/>
          <input className="input with-icon" placeholder="Search videos..." value={q} onChange={e => setQ(e.target.value)}/>
        </div>
      </div>

      <div className="tabs" style={{marginBottom: 20}}>
        {cats.map(c => (
          <button key={c} className={"tab" + (cat === c ? " active" : "")} onClick={() => setCat(c)}>{c}</button>
        ))}
      </div>

      <div className="grid grid-3" style={{gap: 18}}>
        {filtered.map(v => (
          <div key={v.id} className="card" style={{cursor: "pointer", overflow: "hidden", transition: "box-shadow 0.15s"}} onClick={() => setSelected(v.id)}>
            <div style={{background: "linear-gradient(135deg, var(--accent), #5DA399)", height: 160, display: "flex", alignItems: "center", justifyContent: "center", position: "relative"}}>
              <div style={{width: 48, height: 48, borderRadius: "50%", background: "rgba(255,255,255,0.2)", display: "grid", placeItems: "center", color: "white"}}>
                <I.play size={20} style={{marginLeft: 2}}/>
              </div>
              <div style={{position: "absolute", bottom: 8, right: 12, fontSize: 11, color: "white", background: "rgba(0,0,0,0.5)", padding: "2px 8px", borderRadius: 100}} className="mono">{v.duration}</div>
            </div>
            <div className="card-pad">
              <div className="badge" style={{marginBottom: 8, fontSize: 10}}>{v.category}</div>
              <div style={{fontWeight: 600, fontSize: 14, marginBottom: 4, letterSpacing: "-0.01em"}}>{v.title}</div>
              <div className="muted" style={{fontSize: 12}}>{v.date}</div>
            </div>
          </div>
        ))}
      </div>

      {filtered.length === 0 && (
        <div className="section-locked" style={{marginTop: 20}}>
          <I.play size={24}/>
          <div style={{fontWeight: 500}}>No videos match your search</div>
          <div className="muted">Try a different search term or category filter</div>
        </div>
      )}
    </div>
  );
}

// ─── Resource Library (Flow 9) ──────────────────────────────────────
function ResourceLibrary({ go }) {
  const { RESOURCES } = window.MOCK;
  const [cat, setCat] = useState("All");
  const [q, setQ] = useState("");
  const [selected, setSelected] = useState(null);

  const cats = ["All", "Downloads", "Handouts", "Protocol Info"];
  const filtered = RESOURCES.filter(r =>
    (cat === "All" || r.category === cat) &&
    (q === "" || r.title.toLowerCase().includes(q.toLowerCase()))
  );

  if (selected) {
    const r = RESOURCES.find(x => x.id === selected);
    return (
      <div className="page page-narrow" data-screen-label="09 Resource detail">
        <div style={{marginBottom: 18}}>
          <button className="btn sm" onClick={() => setSelected(null)}><I.arrowL size={12}/> Back to library</button>
        </div>
        <div className="card card-pad" style={{padding: "28px 32px"}}>
          <div className="row" style={{gap: 16, marginBottom: 20}}>
            <div style={{width: 56, height: 56, borderRadius: 12, background: "var(--accent-container)", display: "grid", placeItems: "center", color: "var(--accent)"}}>
              <I.doc size={24}/>
            </div>
            <div>
              <h2 style={{fontSize: 20, fontWeight: 700, letterSpacing: "-0.02em", margin: "0 0 4px"}}>{r.title}</h2>
              <div className="row" style={{gap: 8}}>
                <span className="badge">{r.category}</span>
                <span className="muted mono" style={{fontSize: 12}}>{r.type} · {r.size}</span>
              </div>
            </div>
          </div>
          <div className="divider"></div>
          <p style={{color: "var(--text-2)", lineHeight: 1.65, margin: "0 0 24px"}}>{r.description}</p>
          <div className="row" style={{gap: 10}}>
            <button className="btn primary"><I.download size={14}/> Download {r.type}</button>
            <button className="btn"><I.link size={14}/> Copy link</button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="page" data-screen-label="09 Resource library">
      <div className="page-head">
        <div>
          <div className="page-title">Resource Library</div>
          <div className="page-sub">{RESOURCES.length} resources · Downloads, handouts, and protocol references</div>
        </div>
        <div className="input-wrap" style={{width: 280}}>
          <I.search className="lead" size={16}/>
          <input className="input with-icon" placeholder="Search resources..." value={q} onChange={e => setQ(e.target.value)}/>
        </div>
      </div>

      <div className="tabs" style={{marginBottom: 20}}>
        {cats.map(c => (
          <button key={c} className={"tab" + (cat === c ? " active" : "")} onClick={() => setCat(c)}>{c}</button>
        ))}
      </div>

      <div className="card">
        <table className="tbl">
          <thead>
            <tr>
              <th style={{width: 40}}></th>
              <th>Resource</th>
              <th>Category</th>
              <th>Format</th>
              <th>Size</th>
              <th>Date</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(r => (
              <tr key={r.id} className="row-click" onClick={() => setSelected(r.id)}>
                <td>
                  <div style={{width: 32, height: 32, borderRadius: 8, background: "var(--accent-container)", display: "grid", placeItems: "center", color: "var(--accent)"}}>
                    <I.doc size={14}/>
                  </div>
                </td>
                <td><div style={{fontWeight: 500}}>{r.title}</div></td>
                <td><span className="badge">{r.category}</span></td>
                <td className="mono" style={{fontSize: 12}}>{r.type}</td>
                <td className="muted" style={{fontSize: 12}}>{r.size}</td>
                <td className="muted" style={{fontSize: 12}}>{r.date}</td>
                <td style={{textAlign: "right"}}>
                  <button className="btn sm" onClick={e => { e.stopPropagation(); }}><I.download size={12}/> Download</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {filtered.length === 0 && (
        <div className="section-locked" style={{marginTop: 20}}>
          <I.book size={24}/>
          <div style={{fontWeight: 500}}>No resources match your search</div>
          <div className="muted">Try a different search term or category filter</div>
        </div>
      )}
    </div>
  );
}

// ─── Education (Flow 10) ────────────────────────────────────────────
function EducationPage({ go }) {
  const { COURSES } = window.MOCK;
  const [level, setLevel] = useState("All");
  const [selected, setSelected] = useState(null);

  const levels = ["All", "Level 1", "Level 2", "Other Courses"];
  const filtered = COURSES.filter(c => level === "All" || c.level === level);

  if (selected) {
    const c = COURSES.find(x => x.id === selected);
    return (
      <div className="page page-narrow" data-screen-label="10 Course detail">
        <div style={{marginBottom: 18}}>
          <button className="btn sm" onClick={() => setSelected(null)}><I.arrowL size={12}/> Back to courses</button>
        </div>
        <div className="card card-pad" style={{padding: "28px 32px"}}>
          <div className="row" style={{gap: 10, marginBottom: 16}}>
            <span className="badge blue">{c.level}</span>
            <span className="muted" style={{fontSize: 12}}>{c.provider}</span>
          </div>
          <h2 style={{fontSize: 22, fontWeight: 700, letterSpacing: "-0.02em", margin: "0 0 8px"}}>{c.title}</h2>
          <div className="row" style={{gap: 16, marginBottom: 20}}>
            <div className="row" style={{gap: 6}}><I.clock size={14} style={{color: "var(--text-3)"}}/> <span className="muted" style={{fontSize: 13}}>{c.duration}</span></div>
            <div className="row" style={{gap: 6}}><I.book size={14} style={{color: "var(--text-3)"}}/> <span className="muted" style={{fontSize: 13}}>{c.modules} modules</span></div>
          </div>
          <div className="divider"></div>
          <p style={{color: "var(--text-2)", lineHeight: 1.65, margin: "0 0 24px"}}>{c.description}</p>
          <div className="row" style={{gap: 10}}>
            <button className="btn primary"><I.externalLink size={14}/> Go to Course</button>
            <button className="btn"><I.bookmark size={14}/> Save for Later</button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="page" data-screen-label="10 Education">
      <div className="page-head">
        <div>
          <div className="page-title">Education</div>
          <div className="page-sub">{COURSES.length} courses · Clinical HTMA Academy and Vykon Education</div>
        </div>
      </div>

      <div className="tabs" style={{marginBottom: 20}}>
        {levels.map(l => (
          <button key={l} className={"tab" + (level === l ? " active" : "")} onClick={() => setLevel(l)}>{l}</button>
        ))}
      </div>

      <div className="grid grid-2" style={{gap: 18}}>
        {filtered.map(c => (
          <div key={c.id} className="card card-pad" style={{cursor: "pointer", transition: "box-shadow 0.15s"}} onClick={() => setSelected(c.id)}>
            <div className="row" style={{gap: 10, marginBottom: 12}}>
              <div style={{width: 44, height: 44, borderRadius: 10, background: "var(--info-container)", display: "grid", placeItems: "center", color: "var(--info)"}}>
                <I.graduation size={20}/>
              </div>
              <div style={{flex: 1}}>
                <span className="badge blue" style={{fontSize: 10}}>{c.level}</span>
                <div className="muted" style={{fontSize: 11, marginTop: 2}}>{c.provider}</div>
              </div>
              <I.chevR size={14} style={{color: "var(--text-4)"}}/>
            </div>
            <div style={{fontWeight: 600, fontSize: 15, letterSpacing: "-0.01em", marginBottom: 6}}>{c.title}</div>
            <div className="muted" style={{fontSize: 12.5, lineHeight: 1.55, marginBottom: 12}}>{c.description.slice(0, 120)}...</div>
            <div className="row" style={{gap: 14}}>
              <div className="row" style={{gap: 4}}><I.clock size={12} style={{color: "var(--text-4)"}}/> <span className="muted" style={{fontSize: 11.5}}>{c.duration}</span></div>
              <div className="row" style={{gap: 4}}><I.book size={12} style={{color: "var(--text-4)"}}/> <span className="muted" style={{fontSize: 11.5}}>{c.modules} modules</span></div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Support Services (Flow 11) ─────────────────────────────────────
function SupportServices({ go }) {
  const { MENTORS, FAQ_ITEMS } = window.MOCK;
  const [expanded, setExpanded] = useState(null);
  const [mentorDetail, setMentorDetail] = useState(null);

  if (mentorDetail) {
    const m = MENTORS.find(x => x.id === mentorDetail);
    return (
      <div className="page page-narrow" data-screen-label="11 Mentor detail">
        <div style={{marginBottom: 18}}>
          <button className="btn sm" onClick={() => setMentorDetail(null)}><I.arrowL size={12}/> Back to support</button>
        </div>
        <div className="card card-pad" style={{padding: "28px 32px"}}>
          <div className="row" style={{gap: 16, marginBottom: 20}}>
            <Avatar name={m.name} color="var(--accent)" size={56}/>
            <div>
              <h2 style={{fontSize: 20, fontWeight: 700, margin: "0 0 4px"}}>{m.name}</h2>
              <div className="muted">{m.specialty}</div>
            </div>
          </div>
          <div className="divider"></div>
          <p style={{color: "var(--text-2)", lineHeight: 1.65, margin: "0 0 20px"}}>{m.bio}</p>
          <div style={{marginBottom: 20}}>
            <div style={{fontWeight: 600, fontSize: 13, marginBottom: 8}}>Specialization Labs</div>
            <div className="row" style={{gap: 6}}>
              {m.labs.map(l => <span key={l} className="badge green">{l}</span>)}
            </div>
          </div>
          <button className="btn primary"><I.cal size={14}/> Book a Consultation</button>
        </div>
      </div>
    );
  }

  return (
    <div className="page" data-screen-label="11 Support services">
      <div className="page-head">
        <div>
          <div className="page-title">Support Services</div>
          <div className="page-sub">Consultations, mentorship, community, and FAQs</div>
        </div>
      </div>

      {/* Consultation cards */}
      <div style={{marginBottom: 24}}>
        <div style={{fontWeight: 600, fontSize: 15, marginBottom: 12}}>Book a Consultation</div>
        <div className="grid grid-2" style={{gap: 16}}>
          <div className="card card-pad" style={{display: "flex", gap: 16, alignItems: "center"}}>
            <div style={{width: 52, height: 52, borderRadius: 12, background: "var(--accent-container)", display: "grid", placeItems: "center", color: "var(--accent)", flex: "none"}}>
              <I.user size={22}/>
            </div>
            <div style={{flex: 1}}>
              <div style={{fontWeight: 600, marginBottom: 2}}>Human Client Support</div>
              <div className="muted" style={{fontSize: 12.5}}>One-on-one consultation for complex human HTMA cases</div>
            </div>
            <button className="btn primary sm"><I.externalLink size={12}/> Book</button>
          </div>
          <div className="card card-pad" style={{display: "flex", gap: 16, alignItems: "center"}}>
            <div style={{width: 52, height: 52, borderRadius: 12, background: "var(--warn-container)", display: "grid", placeItems: "center", color: "var(--warn)", flex: "none"}}>
              <I.shield size={22}/>
            </div>
            <div style={{flex: 1}}>
              <div style={{fontWeight: 600, marginBottom: 2}}>Animal Client Support</div>
              <div className="muted" style={{fontSize: 12.5}}>Equine and pet HTMA case consultation with specialists</div>
            </div>
            <button className="btn primary sm"><I.externalLink size={12}/> Book</button>
          </div>
        </div>
      </div>

      <div className="grid" style={{gridTemplateColumns: "1fr 1fr", gap: 20}}>
        {/* Mentors */}
        <div>
          <div style={{fontWeight: 600, fontSize: 15, marginBottom: 12}}>Our Mentors</div>
          <div style={{display: "flex", flexDirection: "column", gap: 10}}>
            {MENTORS.map(m => (
              <div key={m.id} className="card card-pad row-click" style={{display: "flex", gap: 14, alignItems: "center", cursor: "pointer"}} onClick={() => setMentorDetail(m.id)}>
                <Avatar name={m.name} color="var(--accent)" size={40}/>
                <div style={{flex: 1, minWidth: 0}}>
                  <div style={{fontWeight: 500}}>{m.name}</div>
                  <div className="muted" style={{fontSize: 12}}>{m.specialty}</div>
                </div>
                <div className="row" style={{gap: 4}}>
                  {m.labs.map(l => <span key={l} className="chip" style={{fontSize: 10}}>{l}</span>)}
                </div>
                <I.chevR size={14} style={{color: "var(--text-4)"}}/>
              </div>
            ))}
          </div>

          {/* Community */}
          <div style={{marginTop: 20}}>
            <div style={{fontWeight: 600, fontSize: 15, marginBottom: 12}}>Community</div>
            <div className="card card-pad" style={{textAlign: "center", padding: "32px 24px"}}>
              <div style={{width: 52, height: 52, borderRadius: "50%", background: "var(--accent-container)", display: "grid", placeItems: "center", color: "var(--accent)", margin: "0 auto 12px"}}>
                <I.globe size={22}/>
              </div>
              <div style={{fontWeight: 600, marginBottom: 4}}>Join the Practitioner Community</div>
              <div className="muted" style={{fontSize: 12.5, marginBottom: 16}}>Connect with fellow practitioners, share insights, and accelerate learning</div>
              <button className="btn primary"><I.externalLink size={14}/> Join Community</button>
            </div>
          </div>
        </div>

        {/* FAQ */}
        <div>
          <div style={{fontWeight: 600, fontSize: 15, marginBottom: 12}}>Frequently Asked Questions</div>
          <div style={{display: "flex", flexDirection: "column", gap: 8}}>
            {FAQ_ITEMS.map((faq, i) => (
              <div key={i} className="card" style={{overflow: "hidden"}}>
                <button
                  style={{display: "flex", alignItems: "center", gap: 12, padding: "14px 18px", width: "100%", background: "none", border: "none", textAlign: "left", cursor: "pointer", fontFamily: "inherit", color: "var(--text)"}}
                  onClick={() => setExpanded(expanded === i ? null : i)}
                >
                  <div style={{flex: 1, fontWeight: 500, fontSize: 13.5}}>{faq.q}</div>
                  {expanded === i ? <I.chevU size={14}/> : <I.chevD size={14}/>}
                </button>
                {expanded === i && (
                  <div style={{padding: "0 18px 16px", color: "var(--text-2)", fontSize: 13, lineHeight: 1.6}}>{faq.a}</div>
                )}
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── News (Flow 12) ─────────────────────────────────────────────────
function NewsPage({ go }) {
  const { NEWS } = window.MOCK;
  const [cat, setCat] = useState("All");
  const [selected, setSelected] = useState(null);

  const cats = ["All", "Product Updates", "Promotions", "Tech Updates"];
  const filtered = NEWS.filter(n =>
    cat === "All" || n.category === cat
  );

  if (selected) {
    const n = NEWS.find(x => x.id === selected);
    return (
      <div className="page page-narrow" data-screen-label="12 Article detail">
        <div style={{marginBottom: 18}}>
          <button className="btn sm" onClick={() => setSelected(null)}><I.arrowL size={12}/> Back to news</button>
        </div>
        <div className="card card-pad" style={{padding: "32px 36px"}}>
          <span className="badge" style={{marginBottom: 12}}>{n.category}</span>
          <h1 style={{fontSize: 24, fontWeight: 700, letterSpacing: "-0.025em", margin: "0 0 8px"}}>{n.title}</h1>
          <div className="muted" style={{fontSize: 13, marginBottom: 24}}>{n.date}</div>
          <div className="divider"></div>
          <p style={{color: "var(--text-2)", lineHeight: 1.75, fontSize: 14.5, margin: "24px 0 0"}}>{n.body}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="page" data-screen-label="12 News">
      <div className="page-head">
        <div>
          <div className="page-title">News</div>
          <div className="page-sub">{NEWS.length} articles · Product updates, promotions, and platform news</div>
        </div>
      </div>

      <div className="tabs" style={{marginBottom: 20}}>
        {cats.map(c => (
          <button key={c} className={"tab" + (cat === c ? " active" : "")} onClick={() => setCat(c)}>{c}</button>
        ))}
      </div>

      <div style={{display: "flex", flexDirection: "column", gap: 12}}>
        {filtered.map(n => (
          <div key={n.id} className="card card-pad row-click" style={{display: "flex", gap: 20, alignItems: "flex-start", cursor: "pointer"}} onClick={() => setSelected(n.id)}>
            <div style={{width: 64, height: 64, borderRadius: 10, background: n.category === "Product Updates" ? "var(--accent-container)" : n.category === "Promotions" ? "var(--warn-container)" : "var(--info-container)", display: "grid", placeItems: "center", color: n.category === "Product Updates" ? "var(--accent)" : n.category === "Promotions" ? "var(--warn)" : "var(--info)", flex: "none"}}>
              <I.newspaper size={24}/>
            </div>
            <div style={{flex: 1, minWidth: 0}}>
              <div className="row" style={{gap: 8, marginBottom: 6}}>
                <span className="badge" style={{fontSize: 10}}>{n.category}</span>
                <span className="muted" style={{fontSize: 12}}>{n.date}</span>
              </div>
              <div style={{fontWeight: 600, fontSize: 15, letterSpacing: "-0.01em", marginBottom: 4}}>{n.title}</div>
              <div className="muted" style={{fontSize: 13, lineHeight: 1.5}}>{n.excerpt}</div>
            </div>
            <I.chevR size={14} style={{color: "var(--text-4)", marginTop: 4}}/>
          </div>
        ))}
      </div>

      {filtered.length === 0 && (
        <div className="section-locked" style={{marginTop: 20}}>
          <I.newspaper size={24}/>
          <div style={{fontWeight: 500}}>No news in this category</div>
        </div>
      )}
    </div>
  );
}

// ─── Platform Admin Dashboard (Flow 12 platform state) ─────────────
function PlatformAdminDashboardView({ go, initialMode = "home", onOpenAIContext }) {
  const [mode, setMode] = useState(initialMode || "home");
  const [selectedClinicId, setSelectedClinicId] = useState("functional-practice");
  const [clinics, setClinics] = useState([
    {
      id: "functional-practice",
      name: "Functional Practice Clinic",
      owner: "Linn Harper",
      status: "Active",
      plan: "Advanced",
      people: 8,
      pending: 1,
      credits: 12,
      sessions: 2,
      lastActivity: "Today, 09:14",
      requestState: "Approved",
    },
    {
      id: "northstar",
      name: "Northstar Wellness",
      owner: "Avery Singh",
      status: "Pending verification",
      plan: "Basic",
      people: 3,
      pending: 2,
      credits: 4,
      sessions: 1,
      lastActivity: "Yesterday, 16:42",
      requestState: "Credential review",
    },
    {
      id: "south-austin",
      name: "South Austin Functional Medicine",
      owner: "Dr. Kira Nolan",
      status: "Setup pending",
      plan: "Premium",
      people: 1,
      pending: 0,
      credits: 20,
      sessions: 0,
      lastActivity: "Jun 25, 11:08",
      requestState: "Clinic creation approved",
    },
  ]);
  const [prototypeEmail, setPrototypeEmail] = useState("");
  const [mentorName, setMentorName] = useState("");
  const [prototypeUsers, setPrototypeUsers] = useState([
    { id: "p1", email: "pilot@functionalpractice.co", status: "Granted", addedBy: "Platform Admin" },
    { id: "p2", email: "reviewer@vykon.ai", status: "Granted", addedBy: "Shaunak" },
  ]);
  const [mentors, setMentors] = useState([
    { id: "m1", name: "Dr. Rowan Ellis", focus: "Complex mineral patterns", access: "Active" },
    { id: "m2", name: "Priya Mentor", focus: "Protocol review support", access: "Active" },
  ]);

  useEffect(() => {
    setMode(initialMode || "home");
  }, [initialMode]);

  const selectedClinic = clinics.find(clinic => clinic.id === selectedClinicId) || clinics[0];
  const activeClinics = clinics.filter(clinic => clinic.status === "Active").length;
  const pendingClinics = clinics.filter(clinic => clinic.status !== "Active").length;
  const totalPeople = clinics.reduce((sum, clinic) => sum + clinic.people, 0);
  const setClinicStatus = (clinicId, status) => {
    setClinics(prev => prev.map(clinic => clinic.id === clinicId ? { ...clinic, status } : clinic));
  };
  const grantPrototypeAccess = () => {
    const email = prototypeEmail.trim().toLowerCase();
    if (!email) return;
    setPrototypeUsers(prev => [
      { id: `p${Date.now()}`, email, status: "Granted", addedBy: "Platform Admin" },
      ...prev.filter(user => user.email !== email),
    ]);
    setPrototypeEmail("");
  };
  const revokePrototypeAccess = id => {
    setPrototypeUsers(prev => prev.map(user => user.id === id ? { ...user, status: user.status === "Granted" ? "Revoked" : "Granted" } : user));
  };
  const addMentor = () => {
    const name = mentorName.trim();
    if (!name) return;
    setMentors(prev => [{ id: `m${Date.now()}`, name, focus: "Clinical support", access: "Active" }, ...prev]);
    setMentorName("");
  };
  const toggleMentor = id => {
    setMentors(prev => prev.map(mentor => mentor.id === id ? { ...mentor, access: mentor.access === "Active" ? "Removed" : "Active" } : mentor));
  };

  const dashboardCards = [
    {
      key: "clinics",
      title: "Manage Clinics",
      desc: "Review all clinic organizations, open a clinic, inspect its people, change role/status, and view active sessions.",
      icon: <I.bldg size={22}/>,
      meta: `${clinics.length} clinics - ${pendingClinics} pending`,
      action: "Open clinics",
    },
    {
      key: "users",
      title: "Manage Users",
      desc: "Grant prototype access and add or remove mentors who support practitioner workflows.",
      icon: <I.users size={22}/>,
      meta: `${prototypeUsers.filter(user => user.status === "Granted").length} prototype users - ${mentors.filter(mentor => mentor.access === "Active").length} mentors`,
      action: "Open users",
    },
    {
      key: "ai-context",
      title: "Manage AI Context",
      desc: "Open the platform-only context management surface for rules, knowledge, memory, and retrieval settings.",
      icon: <I.brain size={22}/>,
      meta: "Rules, knowledge, memory, retrieval",
      action: "Open AI Context",
    },
  ];

  return (
    <div className="page platform-admin-page" data-screen-label="Platform Admin Dashboard">
      <div className="page-head">
        <div>
          <div className="row" style={{gap: 8, marginBottom: 6}}>
            <span className="chip green"><I.shield size={11}/> Platform Admin</span>
            <span className="chip"><I.clock size={11}/> Audit on</span>
          </div>
          <div className="page-title">Admin Dashboard</div>
          <div className="page-sub">Platform-only controls for clinic workspaces, prototype users, mentors, and AI context governance</div>
        </div>
        {mode !== "home" && (
          <button className="btn" onClick={() => setMode("home")}><I.arrowL size={14}/> Dashboard</button>
        )}
      </div>

      {mode === "home" && (
        <>
          <div className="grid grid-3" style={{marginBottom: 18}}>
            <div className="kpi">
              <div className="kpi-label">Active clinics</div>
              <div className="kpi-val">{activeClinics}</div>
              <div className="kpi-trend">{pendingClinics} pending setup or verification</div>
            </div>
            <div className="kpi">
              <div className="kpi-label">Clinic people</div>
              <div className="kpi-val">{totalPeople}</div>
              <div className="kpi-trend">Across managed clinic workspaces</div>
            </div>
            <div className="kpi">
              <div className="kpi-label">Governance</div>
              <div className="kpi-val" style={{fontSize: 24}}>On</div>
              <div className="kpi-trend up">AI context changes require audit trail</div>
            </div>
          </div>

          <div className="platform-admin-cards">
            {dashboardCards.map(card => (
              <div className="card card-pad platform-admin-card" key={card.key}>
                <div className="platform-admin-card-icon">{card.icon}</div>
                <div>
                  <h2>{card.title}</h2>
                  <p>{card.desc}</p>
                  <div className="muted" style={{fontSize: 12.5, marginBottom: 16}}>{card.meta}</div>
                </div>
                <button
                  className="btn primary"
                  onClick={() => card.key === "ai-context" ? (onOpenAIContext ? onOpenAIContext() : go("ai-context-rules")) : setMode(card.key)}
                >
                  {card.action} <I.arrowR size={14}/>
                </button>
              </div>
            ))}
          </div>
        </>
      )}

      {mode === "clinics" && (
        <div className="platform-admin-detail-grid">
          <div className="card">
            <div className="card-head">
              <div>
                <div className="card-title">Clinics</div>
                <div className="card-sub">Organization accounts visible to platform admins</div>
              </div>
            </div>
            <div className="platform-clinic-list">
              {clinics.map(clinic => (
                <button
                  key={clinic.id}
                  className={"platform-clinic-row" + (selectedClinic.id === clinic.id ? " active" : "")}
                  onClick={() => setSelectedClinicId(clinic.id)}
                >
                  <span className="flow-option-icon"><I.bldg size={15}/></span>
                  <span>
                    <strong>{clinic.name}</strong>
                    <small>{clinic.owner} - {clinic.plan} - {clinic.people} people</small>
                  </span>
                  <span className={"badge " + (clinic.status === "Active" ? "green" : "amber")}><span className="dot"></span>{clinic.status}</span>
                </button>
              ))}
            </div>
          </div>

          <div>
            <div className="card card-pad" style={{marginBottom: 16}}>
              <div className="row-between" style={{alignItems: "flex-start", gap: 18}}>
                <div>
                  <div style={{fontWeight: 750, fontSize: 18}}>{selectedClinic.name}</div>
                  <div className="muted" style={{fontSize: 13, marginTop: 3}}>Owner: {selectedClinic.owner} - {selectedClinic.requestState}</div>
                </div>
                <span className={"badge " + (selectedClinic.status === "Active" ? "green" : "amber")}><span className="dot"></span>{selectedClinic.status}</span>
              </div>
              <div className="settings-info-grid" style={{marginTop: 18}}>
                <div><span>Plan</span><strong>{selectedClinic.plan}</strong></div>
                <div><span>People</span><strong>{selectedClinic.people} total - {selectedClinic.pending} pending</strong></div>
                <div><span>Credits</span><strong>{selectedClinic.credits}</strong></div>
                <div><span>Last activity</span><strong>{selectedClinic.lastActivity}</strong></div>
              </div>
              <div className="row" style={{gap: 8, marginTop: 18, flexWrap: "wrap"}}>
                <button className="btn sm" onClick={() => setClinicStatus(selectedClinic.id, selectedClinic.status === "Suspended" ? "Active" : "Suspended")}>
                  <I.shield size={12}/> {selectedClinic.status === "Suspended" ? "Reactivate clinic" : "Suspend clinic"}
                </button>
                <button className="btn sm"><I.clock size={12}/> View active sessions ({selectedClinic.sessions})</button>
                <button className="btn sm"><I.edit size={12}/> Edit platform note</button>
              </div>
            </div>

            <ClinicMemberManagementView go={go} clinicName={selectedClinic.name}/>
          </div>
        </div>
      )}

      {mode === "users" && (
        <div className="platform-users-grid">
          <div className="card card-pad">
            <div className="card-title" style={{marginBottom: 4}}>Prototype Access</div>
            <div className="card-sub" style={{marginBottom: 16}}>Add or remove users from the prototype access list</div>
            <div className="admin-add-row platform-admin-inline-form">
              <input className="input" value={prototypeEmail} placeholder="email@example.com" onChange={e => setPrototypeEmail(e.target.value)}/>
              <button className="btn primary" onClick={grantPrototypeAccess} disabled={!prototypeEmail.trim()}><I.plus size={14}/> Grant access</button>
            </div>
            <div className="platform-simple-list">
              {prototypeUsers.map(user => (
                <div key={user.id} className="platform-simple-row">
                  <div>
                    <strong>{user.email}</strong>
                    <small>Added by {user.addedBy}</small>
                  </div>
                  <div className="row" style={{gap: 8}}>
                    <span className={"badge " + (user.status === "Granted" ? "green" : "red")}><span className="dot"></span>{user.status}</span>
                    <button className="btn sm" onClick={() => revokePrototypeAccess(user.id)}>{user.status === "Granted" ? "Revoke" : "Restore"}</button>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="card card-pad">
            <div className="card-title" style={{marginBottom: 4}}>Mentors</div>
            <div className="card-sub" style={{marginBottom: 16}}>Add or remove mentors shown in support services</div>
            <div className="admin-add-row platform-admin-inline-form">
              <input className="input" value={mentorName} placeholder="Mentor name" onChange={e => setMentorName(e.target.value)}/>
              <button className="btn primary" onClick={addMentor} disabled={!mentorName.trim()}><I.plus size={14}/> Add mentor</button>
            </div>
            <div className="platform-simple-list">
              {mentors.map(mentor => (
                <div key={mentor.id} className="platform-simple-row">
                  <div>
                    <strong>{mentor.name}</strong>
                    <small>{mentor.focus}</small>
                  </div>
                  <div className="row" style={{gap: 8}}>
                    <span className={"badge " + (mentor.access === "Active" ? "green" : "red")}><span className="dot"></span>{mentor.access}</span>
                    <button className="btn sm" onClick={() => toggleMentor(mentor.id)}>{mentor.access === "Active" ? "Remove" : "Restore"}</button>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="card card-pad platform-ai-context-card">
            <div className="platform-admin-card-icon"><I.brain size={22}/></div>
            <div>
              <div className="card-title">AI Context</div>
              <div className="card-sub">Use the existing context management page for rules, knowledge base, memory, and retrieval configuration.</div>
            </div>
            <button className="btn primary" onClick={() => onOpenAIContext ? onOpenAIContext() : go("ai-context-rules")}>Open AI Context <I.arrowR size={14}/></button>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Clinic People And Access Panel ────────────────────────────────
function ClinicMemberManagementView({ go, clinicName = "Functional Practice Clinic" }) {
  const roleOptions = [
    { value: "owner", label: "Clinic Owner" },
    { value: "admin", label: "Clinic Admin" },
    { value: "practitioner", label: "Practitioner" },
    { value: "assistant", label: "Practitioner Assistant" },
  ];
  const statusOptions = [
    { value: "pending_invitation", label: "Pending invitation" },
    { value: "pending_verification", label: "Pending verification" },
    { value: "active", label: "Active" },
    { value: "suspended", label: "Suspended" },
    { value: "archived", label: "Archived" },
  ];
  const [email, setEmail] = useState("");
  const [role, setRole] = useState("practitioner");
  const [credentialStatus, setCredentialStatus] = useState("pending_verification");
  const [expanded, setExpanded] = useState("u1");
  const [confirmUser, setConfirmUser] = useState(null);
  const [users, setUsers] = useState([
    {
      id: "u1",
      name: "Linn",
      email: "linn@functionalpractice.co",
      role: "owner",
      membershipRole: "owner",
      status: "active",
      credentialStatus: "verified",
      clientScope: "All clinic clients, recommendations, orders, reporting",
      policy: "Highest clinic role · inherits Admin permissions · verified owner inherits Practitioner permissions",
      createdAt: "24/06/2026",
      canRemove: false,
      canTransferOwner: true,
      sessions: [
        {
          id: "s1",
          updatedAt: "24/06/2026, 09:14",
          createdAt: "24/06/2026, 08:03",
          expiresAt: "01/07/2026, 08:03",
          ip: "172.16.18.24",
          device: "Chrome 126 on macOS",
        },
      ],
    },
    {
      id: "u2",
      name: "Maya Chen",
      email: "maya@functionalpractice.co",
      role: "admin",
      membershipRole: "admin",
      status: "active",
      credentialStatus: "not_clinical",
      clientScope: "All clinic clients and orders",
      policy: "Operational role · cannot own clinic, transfer ownership, manage clinic profile, or approve clinical content",
      createdAt: "21/06/2026",
      canRemove: true,
      canTransferOwner: false,
      sessions: [
        {
          id: "s2",
          updatedAt: "23/06/2026, 16:42",
          createdAt: "23/06/2026, 15:51",
          expiresAt: "30/06/2026, 15:51",
          ip: "10.0.4.11",
          device: "Safari on iPadOS",
        },
      ],
    },
    {
      id: "u3",
      name: null,
      email: "jordan@functionalpractice.co",
      role: "practitioner",
      membershipRole: "practitioner",
      status: "pending_verification",
      credentialStatus: "pending_verification",
      clientScope: "Assigned clients after approval",
      policy: "Can invite/approve/decline/edit/suspend assigned clients after credential approval",
      createdAt: "19/06/2026",
      canRemove: true,
      canTransferOwner: false,
      sessions: [],
    },
    {
      id: "u4",
      name: "Riley Park",
      email: "riley@functionalpractice.co",
      role: "assistant",
      membershipRole: "assistant",
      status: "active",
      credentialStatus: "not_clinical",
      clientScope: "Delegated clients under Jordan Lee",
      policy: "Minimum view clients/view recommendations/send drafts; optional edit, communication, and order permissions granted by practitioner",
      assistantPermissions: ["View", "Edit profile", "Communication", "Order support"],
      createdAt: "18/06/2026",
      canRemove: true,
      canTransferOwner: false,
      sessions: [],
    },
  ]);
  const pendingCount = users.filter(user => user.status === "pending_invitation" || user.status === "pending_verification").length;

  const roleLabel = value => roleOptions.find(option => option.value === value)?.label || value;
  const statusLabel = value => statusOptions.find(option => option.value === value)?.label || value;
  const credentialLabel = value => ({
    verified: "Verified practitioner",
    pending_verification: "Credential review pending",
    not_clinical: "No clinical approval",
  }[value] || value);
  const defaultCredentialStatus = value => value === "owner" || value === "practitioner" ? "pending_verification" : "not_clinical";
  const defaultScope = value => ({
    owner: "All clinic clients, recommendations, orders, reporting",
    admin: "All clinic clients and orders",
    practitioner: "Assigned clients after approval",
    assistant: "Delegated clients under practitioner",
  }[value] || "Clinic member");
  const defaultPolicy = value => ({
    owner: "Highest clinic role · inherits Admin permissions · verified owner inherits Practitioner permissions",
    admin: "Operational role · cannot own clinic, transfer ownership, manage clinic profile, or approve clinical content",
    practitioner: "Assigned-client clinical role · manages assigned clients and assistant permissions after approval",
    assistant: "Delegated support role · minimum view/recommendation/draft access plus optional edit/communication/order permissions",
  }[value] || "Role-scoped clinic access");
  const rolePolicies = [
    {
      role: "Clinic Owner",
      can: "Manage clinic settings/profile, all practitioners, assistants, clients, assignments, reporting, payment method, ownership transfer, and clinical recommendations when verified.",
      cannot: "Be archived or removed until ownership is transferred. Unverified owner cannot approve clinical recommendations.",
    },
    {
      role: "Clinic Admin",
      can: "Invite/edit/suspend/archive practitioners, assistants, and clients; assign clients; view recommendations/orders; support communication and ordering.",
      cannot: "Be owner, transfer ownership, manage clinic profile/settings, create/edit/approve clinical recommendations, or alter clinical content.",
    },
    {
      role: "Practitioner",
      can: "Invite/approve/decline/edit/suspend assigned clients, create/edit/approve assigned-client recommendations, place orders, and grant assistant permissions.",
      cannot: "Archive clients, manage practitioners outside assigned assistants, access other practitioners' clients unless granted, manage clinic settings, or operate as both an individual and clinic practitioner.",
    },
    {
      role: "Practitioner Assistant",
      can: "Minimum view assigned clients, view recommendations, and send drafts. Optional communication, profile edit, send-to-order, and order placement.",
      cannot: "Approve recommendations, create final recommendations, archive clients, manage users, or access clinic settings/profile.",
    },
  ];
  const statusClass = value => value === "active" ? "green" : value === "suspended" || value === "archived" ? "red" : "amber";
  const setRowRole = (id, nextRole) => {
    setUsers(prev => prev.map(user => (
      user.id === id
        ? {
            ...user,
            role: nextRole,
            membershipRole: nextRole,
            credentialStatus: defaultCredentialStatus(nextRole),
            clientScope: defaultScope(nextRole),
            policy: defaultPolicy(nextRole),
            assistantPermissions: nextRole === "assistant" ? ["View", "Send drafts"] : undefined,
          }
        : user
    )));
  };
  const setRowStatus = (id, nextStatus) => {
    setUsers(prev => prev.map(user => user.id === id ? { ...user, status: nextStatus } : user));
  };
  const saveEntry = () => {
    const normalizedEmail = email.trim().toLowerCase();
    if (!normalizedEmail) return;
    setUsers(prev => {
      const existing = prev.find(user => user.email === normalizedEmail);
      if (existing) {
        return prev.map(user => user.email === normalizedEmail ? {
          ...user,
          role,
          membershipRole: role,
          credentialStatus,
          clientScope: defaultScope(role),
          policy: defaultPolicy(role),
          assistantPermissions: role === "assistant" ? ["View", "Send drafts"] : undefined,
        } : user);
      }
      return [
        {
          id: `u${Date.now()}`,
          name: null,
          email: normalizedEmail,
          role,
          membershipRole: role,
          status: "pending_invitation",
          credentialStatus,
          clientScope: defaultScope(role),
          policy: defaultPolicy(role),
          assistantPermissions: role === "assistant" ? ["View", "Send drafts"] : undefined,
          createdAt: "24/06/2026",
          canRemove: true,
          canTransferOwner: false,
          sessions: [],
        },
        ...prev,
      ];
    });
    setEmail("");
  };
  const removeUser = user => {
    if (!user.canRemove) return;
    setUsers(prev => prev.map(row => row.id === user.id ? { ...row, status: "archived", sessions: [] } : row));
    setConfirmUser(null);
  };

  return (
    <div className="admin-users-view">
      <div className="row-between admin-users-title">
        <div>
          <h2>Clinic People & Access</h2>
          <div className="muted" style={{fontSize: 13}}>Manage people inside {clinicName}, assign clinic roles, manage membership status, and inspect active sessions. Client access remains clinic-owned and assignment-scoped.</div>
        </div>
        <div className="admin-users-count">
          <strong>{users.length}</strong>
          <span>{pendingCount} pending</span>
        </div>
      </div>

      <div className="card card-pad admin-add-card">
        <div style={{fontWeight: 700, fontSize: 15}}>Invite Or Update Clinic Member</div>
        <div className="admin-add-row">
          <input
            className="input"
            value={email}
            placeholder="email@example.com"
            onChange={e => setEmail(e.target.value)}
          />
          <select
            className="select"
            value={role}
            onChange={e => {
              const nextRole = e.target.value;
              setRole(nextRole);
              setCredentialStatus(defaultCredentialStatus(nextRole));
            }}
          >
            {roleOptions.map(option => <option key={option.value} value={option.value}>{option.label}</option>)}
          </select>
          <select
            className="select"
            value={credentialStatus}
            onChange={e => setCredentialStatus(e.target.value)}
          >
            <option value="verified">Verified practitioner</option>
            <option value="pending_verification">Credential review pending</option>
            <option value="not_clinical">No clinical approval</option>
          </select>
          <button className="btn primary" disabled={!email.trim()} onClick={saveEntry}>
            <I.plus size={14}/> Send invite
          </button>
        </div>
        <div className="permission-tags" style={{marginTop: 12}}>
          <span><I.shield size={12}/> {roleLabel(role)}</span>
          <span><I.clock size={12}/> Starts as Pending invitation</span>
          <span><I.file size={12}/> {credentialLabel(credentialStatus)}</span>
        </div>
      </div>

      <div className="role-policy-grid">
        {rolePolicies.map(item => (
          <div className="role-policy-card" key={item.role}>
            <strong>{item.role}</strong>
            <span><b>Can:</b> {item.can}</span>
            <span><b>Cannot:</b> {item.cannot}</span>
          </div>
        ))}
      </div>

      <div className="admin-users-list">
        {users.map(user => {
          const roleChanged = user.membershipRole && user.membershipRole !== user.role;
          const hasSessions = user.sessions.length > 0;
          const sessionsExpanded = expanded === user.id;
          return (
            <div className="card card-pad admin-user-card" key={user.id}>
              <div className="row-between admin-user-main">
                <div className="admin-user-identity">
                  <div className="admin-user-name">{user.name || user.email}</div>
                  <div className="muted">{user.email}</div>
                  <div className="row" style={{gap: 8, flexWrap: "wrap", marginTop: 7}}>
                    <span className={"badge " + statusClass(user.status)}><span className="dot"></span>{statusLabel(user.status)}</span>
                    <span className={"badge " + (user.credentialStatus === "verified" ? "green" : user.credentialStatus === "not_clinical" ? "blue" : "amber")}><span className="dot"></span>{credentialLabel(user.credentialStatus)}</span>
                    {roleChanged && <span className="badge amber"><span className="dot"></span>Membership role: {roleLabel(user.membershipRole)}</span>}
                  </div>
                </div>
                <div className="admin-user-controls">
                  <select className="select" value={user.role} onChange={e => setRowRole(user.id, e.target.value)}>
                    {roleOptions.map(option => <option key={option.value} value={option.value}>{option.label}</option>)}
                  </select>
                  <select className="select" value={user.status} onChange={e => setRowStatus(user.id, e.target.value)}>
                    {statusOptions.map(option => <option key={option.value} value={option.value}>{option.label}</option>)}
                  </select>
                  {user.status === "pending_invitation" && (
                    <button className="btn sm"><I.refresh size={12}/> Resend</button>
                  )}
                  {user.canTransferOwner && (
                    <button className="btn sm"><I.shield size={12}/> Transfer</button>
                  )}
                  <button
                    className="btn sm"
                    disabled={!user.canRemove}
                    title={user.canRemove ? "Archive member" : "Transfer ownership before removing owner"}
                    onClick={() => setConfirmUser(user)}
                  >
                    <I.trash size={13}/>
                  </button>
                </div>
              </div>

              <div className="admin-user-meta">
                <span>Org role: {roleLabel(user.role)}</span>
                <span>Scope: {user.clientScope}</span>
                <span>Added: {user.createdAt}</span>
                <button className="btn sm" disabled={!hasSessions} onClick={() => setExpanded(sessionsExpanded ? null : user.id)}>
                  {hasSessions ? (sessionsExpanded ? "Hide sessions" : `Active sessions (${user.sessions.length})`) : "No active sessions"}
                </button>
              </div>

              <div className="admin-rule-panel">
                <div>
                  <span>Access rule</span>
                  <strong>{user.policy}</strong>
                </div>
                {user.role === "assistant" && (
                  <div>
                    <span>Assistant permissions</span>
                    <div className="permission-tags">
                      {(user.assistantPermissions || ["View", "Send drafts"]).map(permission => <em key={permission}>{permission}</em>)}
                    </div>
                  </div>
                )}
                {user.role === "owner" && (
                  <div>
                    <span>Owner guardrail</span>
                    <strong>One active owner is required. Transfer ownership before archive/removal.</strong>
                  </div>
                )}
              </div>

              {sessionsExpanded && hasSessions && (
                <div className="admin-session-list">
                  {user.sessions.map(session => (
                    <div className="admin-session" key={session.id}>
                      <strong>Last active: {session.updatedAt}</strong>
                      <span>Started: {session.createdAt}</span>
                      <span>Expires: {session.expiresAt}</span>
                      <span>IP: {session.ip}</span>
                      <small>{session.device}</small>
                    </div>
                  ))}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {confirmUser && (
        <div className="modal-backdrop" onClick={() => setConfirmUser(null)}>
          <div className="modal" onClick={e => e.stopPropagation()} style={{maxWidth: 420}}>
            <div className="row" style={{gap: 10, marginBottom: 8}}><I.trash size={18}/><h3 style={{margin: 0}}>Archive member?</h3></div>
            <p className="muted" style={{margin: "0 0 20px", fontSize: 13.5}}>{confirmUser.email} will lose access to this clinic organization. Historical attribution stays attached to previous actions.</p>
            <div className="row" style={{justifyContent: "flex-end", gap: 8}}>
              <button className="btn ghost" onClick={() => setConfirmUser(null)}>Cancel</button>
              <button className="btn primary" onClick={() => removeUser(confirmUser)}>Archive</button>
            </div>
          </div>
        </div>
      )}

      <div className="card card-pad client-onboarding-strip">
        <div>
          <strong>Client onboarding model</strong>
          <span>Practitioner or Clinic Admin creates the client, enters name, shipping address, phone, email, payment information, assigns a primary practitioner, and sends the profile invitation.</span>
        </div>
        <button className="btn sm" onClick={() => go("clients")}><I.users size={12}/> Open clients</button>
      </div>
    </div>
  );
}

// ─── Settings (Flow 12 + org planning views) ───────────────────────
function SettingsPage({ go, initialSection = "account", initialAdminMode = "home", initialAiContextSection = "rules", editProfileRequest = 0 }) {
  const [section, setSection] = useState(initialSection || "account");
  const [theme, setTheme] = useState("light");
  const [notifs, setNotifs] = useState(true);
  const [editingProfile, setEditingProfile] = useState(false);
  const [profileName, setProfileName] = useState("Linn");
  const [profileEmail, setProfileEmail] = useState("linn@functionalpractice.co");
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [showLogoutConfirm, setShowLogoutConfirm] = useState(false);
  const [certFile, setCertFile] = useState("FNTP_Certificate_2024.pdf");
  const [mailingList, setMailingList] = useState(true);
  const teamMembers = [
    { name: "Linn", email: "linn@functionalpractice.co", role: "Owner", status: "Active", lastActive: "Today" },
    { name: "Maya Chen", email: "maya@functionalpractice.co", role: "Admin", status: "Active", lastActive: "Yesterday" },
    { name: "Jordan Lee", email: "jordan@functionalpractice.co", role: "Practitioner", status: "Active", lastActive: "Jun 22" },
    { name: "Priya Shah", email: "priya@functionalpractice.co", role: "Practitioner", status: "Pending invitation", lastActive: "Invited" },
  ];
  const creditEvents = [
    { date: "Jun 24", event: "Protocol generation reserved", actor: "Linn", delta: "-1", balance: "12" },
    { date: "Jun 21", event: "VERA case assistant", actor: "Maya Chen", delta: "-1", balance: "13" },
    { date: "Jun 15", event: "Monthly team allocation", actor: "System", delta: "+15", balance: "14" },
  ];

  useEffect(() => {
    if (initialSection === "logout") {
      setSection("account");
      setShowLogoutConfirm(true);
      return;
    }
    setSection(initialSection || "account");
    if (editProfileRequest) setEditingProfile(true);
  }, [initialSection, editProfileRequest]);

  const sections = [
    { k: "admin-dashboard", label: "Admin Dashboard", icon: <I.shield size={16}/> },
    { k: "ai-context", label: "AI Context", icon: <I.brain size={16}/> },
    { k: "account", label: "Account", icon: <I.user size={16}/> },
    { k: "organization", label: "Organization", icon: <I.bldg size={16}/> },
    { k: "team-access", label: "Team & Access", icon: <I.users size={16}/> },
    { k: "subscription", label: "Subscription", icon: <I.receipt size={16}/> },
    { k: "credits", label: "Credits & Usage", icon: <I.bolt size={16}/> },
    { k: "account-mgmt", label: "Account Management", icon: <I.bldg size={16}/> },
    { k: "support-links", label: "Support", icon: <I.help size={16}/> },
    { k: "logout", label: "Log Out", icon: <I.logout size={16}/>, danger: true },
  ];

  function Toggle({ on, onToggle }) {
    return (
      <div style={{width: 38, height: 22, borderRadius: 11, background: on ? "var(--accent)" : "var(--surface-2)", padding: 2, cursor: "pointer", transition: "background .15s"}} onClick={onToggle}>
        <div style={{width: 18, height: 18, borderRadius: 9, background: "#fff", transform: on ? "translateX(16px)" : "translateX(0)", transition: "transform .15s", boxShadow: "0 1px 3px rgba(0,0,0,.15)"}}></div>
      </div>
    );
  }

  return (
    <div className="settings-layout">
      <div className="settings-sidebar">
        <div style={{fontWeight: 700, fontSize: 15, padding: "0 14px 16px"}}>Settings</div>
        {sections.map(s => (
          <button
            key={s.k}
            className={"nav-item" + (section === s.k ? " active" : "")}
            style={s.danger ? {color: "var(--danger)"} : {}}
            onClick={() => {
              if (s.k === "logout") { setShowLogoutConfirm(true); return; }
              setSection(s.k);
            }}
          >
            <span className="ico">{s.icon}</span>
            <span>{s.label}</span>
          </button>
        ))}
      </div>

      <div className="settings-content">
        {section === "admin-dashboard" && (
          <PlatformAdminDashboardView go={go} initialMode={initialAdminMode} onOpenAIContext={() => setSection("ai-context")}/>
        )}

        {section === "ai-context" && (
          <AIContextPage key={initialAiContextSection} initialSection={initialAiContextSection}/>
        )}

        {section === "account" && (
          <div style={{maxWidth: 640}}>
            <h2 style={{fontSize: 18, fontWeight: 700, margin: "0 0 4px"}}>Account</h2>
            <div className="muted" style={{fontSize: 13, marginBottom: 24}}>Theme, notifications, and profile settings</div>

            <div className="card card-pad" style={{marginBottom: 16}}>
              <div style={{display: "flex", alignItems: "center", gap: 14, padding: "4px 0", marginBottom: 14}}>
                <div style={{flex: 1}}>
                  <div style={{fontWeight: 500, fontSize: 14}}>Theme</div>
                  <div className="muted" style={{fontSize: 12.5}}>Switch between light and dark appearance</div>
                </div>
                <div className="row" style={{gap: 4, background: "var(--surface-1)", borderRadius: 8, padding: 3}}>
                  <button className={"btn sm" + (theme === "light" ? " primary" : " ghost")} onClick={() => setTheme("light")} style={{fontSize: 12}}>Light</button>
                  <button className={"btn sm" + (theme === "dark" ? " primary" : " ghost")} onClick={() => setTheme("dark")} style={{fontSize: 12}}>Dark</button>
                </div>
              </div>

              <div style={{display: "flex", alignItems: "center", gap: 14, padding: "4px 0", borderTop: "1px solid var(--border)", paddingTop: 14}}>
                <div style={{flex: 1}}>
                  <div style={{fontWeight: 500, fontSize: 14}}>Push Notifications</div>
                  <div className="muted" style={{fontSize: 12.5}}>Receive browser notifications for case updates</div>
                </div>
                <Toggle on={notifs} onToggle={() => setNotifs(!notifs)}/>
              </div>
            </div>

            <div className="card card-pad">
              <div className="row-between" style={{marginBottom: 16}}>
                <div>
                  <div style={{fontWeight: 600, fontSize: 14}}>Edit Profile</div>
                  <div className="muted" style={{fontSize: 12.5}}>Name, avatar, and email display</div>
                </div>
                {!editingProfile && <button className="btn sm" onClick={() => setEditingProfile(true)}><I.edit size={12}/> Edit</button>}
              </div>

              {!editingProfile ? (
                <div className="row" style={{gap: 16}}>
                  <Avatar initial="L" color="oklch(0.62 0.14 240)" size={56}/>
                  <div style={{display: "grid", gridTemplateColumns: "auto 1fr", gap: "8px 16px", fontSize: 13.5}}>
                    <div className="muted">Name</div><div>{profileName}</div>
                    <div className="muted">Email</div><div>{profileEmail}</div>
                    <div className="muted">Role</div><div>FNTP · Vykon Pro</div>
                  </div>
                </div>
              ) : (
                <div>
                  <div className="row" style={{gap: 16, marginBottom: 16}}>
                    <Avatar initial="L" color="oklch(0.62 0.14 240)" size={56}/>
                    <button className="btn sm">Change avatar</button>
                  </div>
                  <div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 16}}>
                    <div className="field">
                      <div className="field-label">Display name</div>
                      <input className="input" value={profileName} onChange={e => setProfileName(e.target.value)}/>
                    </div>
                    <div className="field">
                      <div className="field-label">Email</div>
                      <input className="input" value={profileEmail} onChange={e => setProfileEmail(e.target.value)}/>
                    </div>
                  </div>
                  <div className="row" style={{gap: 8, justifyContent: "flex-end"}}>
                    <button className="btn ghost" onClick={() => setEditingProfile(false)}>Cancel</button>
                    <button className="btn primary" onClick={() => setEditingProfile(false)}><I.check size={14}/> Save changes</button>
                  </div>
                </div>
              )}
            </div>
          </div>
        )}

        {section === "organization" && (
          <div style={{maxWidth: 960}}>
            <h2 style={{fontSize: 18, fontWeight: 700, margin: "0 0 4px"}}>Organization</h2>
            <div className="muted" style={{fontSize: 13, marginBottom: 24}}>Clinic workspace, role context, subscription status, and usage snapshot</div>

            <div className="grid grid-3" style={{marginBottom: 16}}>
              <div className="kpi">
                <div className="kpi-label">Active clinic</div>
                <div className="kpi-val" style={{fontSize: 22}}>Functional Practice</div>
                <div className="kpi-trend">Owner: Linn · Practitioner workspace</div>
              </div>
              <div className="kpi">
                <div className="kpi-label">Plan status</div>
                <div className="kpi-val" style={{fontSize: 22}}>Vykon Pro</div>
                <div className="kpi-trend up">Current · renews Jul 24</div>
              </div>
              <div className="kpi">
                <div className="kpi-label">Credits</div>
                <div className="kpi-val">12</div>
                <div className="kpi-trend">Protocol and full VERA actions</div>
              </div>
            </div>

            <div className="card card-pad" style={{marginBottom: 16}}>
              <div className="row-between" style={{alignItems: "flex-start", gap: 16}}>
                <div>
                  <div style={{fontWeight: 650, fontSize: 15}}>Functional Practice Clinic</div>
                  <div className="muted" style={{fontSize: 12.5, marginTop: 3}}>Clinical workspace for HTMA practitioners and support staff</div>
                </div>
                <span className="badge green"><span className="dot"></span> Active</span>
              </div>
              <div className="settings-info-grid" style={{marginTop: 18}}>
                <div><span>Workspace ID</span><strong>org_fpc_001</strong></div>
                <div><span>Primary role</span><strong>Practitioner</strong></div>
                <div><span>Billing owner</span><strong>Maya Chen</strong></div>
                <div><span>Seats</span><strong>8 of 10 used</strong></div>
              </div>
            </div>

            <div className="card card-pad">
              <div className="row-between" style={{marginBottom: 14}}>
                <div>
                  <div style={{fontWeight: 650, fontSize: 14}}>Organization switcher</div>
                  <div className="muted" style={{fontSize: 12.5}}>Shown when a user belongs to multiple clinics</div>
                </div>
                <button className="btn sm"><I.chevD size={12}/> Switch clinic</button>
              </div>
              <div className="org-switch-list">
                <div className="org-switch-row active"><I.bldg size={15}/><span>Functional Practice Clinic</span><small>Practitioner · Active</small></div>
                <div className="org-switch-row"><I.bldg size={15}/><span>Northstar Wellness</span><small>Admin · Active</small></div>
              </div>
            </div>
          </div>
        )}

        {section === "team-access" && (
          <div style={{maxWidth: 960}}>
            <h2 style={{fontSize: 18, fontWeight: 700, margin: "0 0 4px"}}>Team & Access</h2>
            <div className="muted" style={{fontSize: 13, marginBottom: 24}}>Invite clinic members, assign roles, and manage membership status</div>

            <div className="alert info" style={{marginBottom: 16}}>
              <I.users size={16}/>
              <div><strong>Seat usage:</strong> 8 of 10 seats are active. Inviting another practitioner is allowed.</div>
            </div>

            <div className="card">
              <div className="card-head">
                <div>
                  <div className="card-title">Clinic members</div>
                  <div className="card-sub">Role-aware access control for the active organization</div>
                </div>
                <button className="btn primary sm"><I.plus size={12}/> Invite member</button>
              </div>
              <table className="tbl">
                <thead>
                  <tr>
                    <th>User</th>
                    <th>Role</th>
                    <th>Status</th>
                    <th>Last active</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  {teamMembers.map(member => (
                    <tr key={member.email}>
                      <td>
                        <div style={{fontWeight: 500}}>{member.name}</div>
                        <div className="muted" style={{fontSize: 11.5}}>{member.email}</div>
                      </td>
                      <td>{member.role}</td>
                      <td><span className={"badge " + (member.status === "Active" ? "green" : "amber")}><span className="dot"></span> {member.status}</span></td>
                      <td className="muted">{member.lastActive}</td>
                      <td style={{textAlign: "right"}}><button className="btn sm ghost"><I.more size={14}/></button></td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {section === "subscription" && (
          <div style={{maxWidth: 960}}>
            <h2 style={{fontSize: 18, fontWeight: 700, margin: "0 0 4px"}}>Subscription</h2>
            <div className="muted" style={{fontSize: 13, marginBottom: 24}}>Plan, billing status, invoices, and blocked-state handling</div>

            <div className="grid grid-2" style={{marginBottom: 16}}>
              <div className="card card-pad subscription-card">
                <div className="row-between" style={{marginBottom: 18}}>
                  <div>
                    <div style={{fontWeight: 700, fontSize: 20}}>Vykon Pro</div>
                    <div className="muted" style={{fontSize: 12.5}}>Clinic plan · 10 seats · protocol credits included</div>
                  </div>
                  <span className="badge green"><span className="dot"></span> Current</span>
                </div>
                <div className="settings-info-grid compact">
                  <div><span>Renews</span><strong>Jul 24, 2026</strong></div>
                  <div><span>Payment method</span><strong>Visa ending 4242</strong></div>
                  <div><span>Seats</span><strong>8 / 10</strong></div>
                  <div><span>Billing owner</span><strong>Maya Chen</strong></div>
                </div>
                <div className="row" style={{gap: 8, marginTop: 18}}>
                  <button className="btn sm primary"><I.externalLink size={12}/> Manage billing</button>
                  <button className="btn sm">Change plan</button>
                </div>
              </div>

              <div className="card card-pad" style={{borderColor: "var(--warn-container)"}}>
                <div style={{fontWeight: 650, fontSize: 14, marginBottom: 8}}>Past-due blocked state</div>
                <div className="muted" style={{fontSize: 12.5, lineHeight: 1.55}}>If billing becomes inactive, the portal still explains the issue, but paid actions such as protocol generation and full VERA are blocked until an admin resolves billing.</div>
                <div className="alert warn" style={{marginTop: 14}}>
                  <I.warn size={16}/>
                  <div>Billing action required before metered clinical actions can continue.</div>
                </div>
              </div>
            </div>

            <div className="card">
              <div className="card-head">
                <div className="card-title">Invoices</div>
                <button className="btn sm"><I.download size={12}/> Download all</button>
              </div>
              <table className="tbl">
                <tbody>
                  {["Jun 2026", "May 2026", "Apr 2026"].map((month, i) => (
                    <tr key={month}>
                      <td>{month}</td>
                      <td className="muted">Vykon Pro subscription</td>
                      <td><span className="badge green"><span className="dot"></span> Paid</span></td>
                      <td style={{textAlign: "right"}}>${i === 0 ? "249.00" : "249.00"}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {section === "credits" && (
          <div style={{maxWidth: 960}}>
            <h2 style={{fontSize: 18, fontWeight: 700, margin: "0 0 4px"}}>Credits & Usage</h2>
            <div className="muted" style={{fontSize: 13, marginBottom: 24}}>Credit balance, reservations, and metered action history</div>

            <div className="grid grid-3" style={{marginBottom: 16}}>
              <div className="kpi">
                <div className="kpi-label">Available credits</div>
                <div className="kpi-val">12</div>
                <div className="kpi-trend up">Enough for protocol generation</div>
              </div>
              <div className="kpi">
                <div className="kpi-label">Reserved</div>
                <div className="kpi-val">1</div>
                <div className="kpi-trend">Held for active protocol job</div>
              </div>
              <div className="kpi">
                <div className="kpi-label">Used this month</div>
                <div className="kpi-val">8</div>
                <div className="kpi-trend">6 protocols · 2 VERA sessions</div>
              </div>
            </div>

            <div className="card card-pad" style={{marginBottom: 16}}>
              <div className="row-between">
                <div>
                  <div style={{fontWeight: 650, fontSize: 14}}>Insufficient-credit blocked state</div>
                  <div className="muted" style={{fontSize: 12.5, marginTop: 3}}>Shown when a paid action does not have available organization credits.</div>
                </div>
                <button className="btn primary sm"><I.plus size={12}/> Add credits</button>
              </div>
            </div>

            <div className="card">
              <div className="card-head">
                <div>
                  <div className="card-title">Credit ledger</div>
                  <div className="card-sub">Reservations and completed usage events</div>
                </div>
              </div>
              <table className="tbl">
                <thead>
                  <tr>
                    <th>Date</th>
                    <th>Event</th>
                    <th>Actor</th>
                    <th>Delta</th>
                    <th>Balance</th>
                  </tr>
                </thead>
                <tbody>
                  {creditEvents.map(event => (
                    <tr key={event.date + event.event}>
                      <td>{event.date}</td>
                      <td>{event.event}</td>
                      <td className="muted">{event.actor}</td>
                      <td style={{color: event.delta.startsWith("+") ? "var(--accent)" : "var(--text)"}}>{event.delta}</td>
                      <td>{event.balance}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {section === "account-mgmt" && (
          <div style={{maxWidth: 640}}>
            <h2 style={{fontSize: 18, fontWeight: 700, margin: "0 0 4px"}}>Account Management</h2>
            <div className="muted" style={{fontSize: 13, marginBottom: 24}}>Personal information, address, accreditation, and communication preferences</div>

            <div className="card card-pad" style={{marginBottom: 16}}>
              <div className="row-between" style={{marginBottom: 14}}>
                <div style={{fontWeight: 600, fontSize: 14}}>Account Information</div>
                <button className="btn sm ghost"><I.edit size={11}/> Edit</button>
              </div>
              <div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12}}>
                <div className="field"><div className="field-label">First name</div><input className="input" defaultValue="Linn" readOnly/></div>
                <div className="field"><div className="field-label">Last name</div><input className="input" defaultValue="" placeholder="—" readOnly/></div>
                <div className="field"><div className="field-label">Email</div><input className="input" defaultValue="linn@functionalpractice.co" readOnly/></div>
                <div className="field"><div className="field-label">Phone</div><input className="input" defaultValue="+1 (604) 555-0199" readOnly/></div>
              </div>
            </div>

            <div className="card card-pad" style={{marginBottom: 16}}>
              <div className="row-between" style={{marginBottom: 14}}>
                <div style={{fontWeight: 600, fontSize: 14}}>Address Information</div>
                <button className="btn sm ghost"><I.edit size={11}/> Edit</button>
              </div>
              <div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12}}>
                <div className="field"><div className="field-label">Address name</div><input className="input" defaultValue="Practice" readOnly/></div>
                <div className="field"><div className="field-label">Phone</div><input className="input" defaultValue="+1 (604) 555-0199" readOnly/></div>
                <div className="field" style={{gridColumn: "1 / -1"}}><div className="field-label">Street</div><input className="input" defaultValue="1234 Wellness Drive" readOnly/></div>
                <div className="field"><div className="field-label">City</div><input className="input" defaultValue="Vancouver" readOnly/></div>
                <div className="field"><div className="field-label">Country</div><input className="input" defaultValue="Canada" readOnly/></div>
                <div className="field"><div className="field-label">State / Province</div><input className="input" defaultValue="BC" readOnly/></div>
                <div className="field"><div className="field-label">Zip / Postal code</div><input className="input" defaultValue="V6K 2G3" readOnly/></div>
              </div>
            </div>

            <div className="card card-pad" style={{marginBottom: 16}}>
              <div style={{fontWeight: 600, fontSize: 14, marginBottom: 14}}>Accreditation Information</div>
              <div style={{display: "flex", alignItems: "center", gap: 14, padding: "12px 16px", background: "var(--surface-1)", borderRadius: 8, marginBottom: 12}}>
                <I.file size={18} style={{color: "var(--accent)", flex: "none"}}/>
                <div style={{flex: 1}}>
                  <div style={{fontWeight: 500, fontSize: 13}}>{certFile}</div>
                  <div className="muted" style={{fontSize: 11.5}}>Current certificate · Uploaded Jan 2024</div>
                </div>
                <button className="btn sm ghost" style={{color: "var(--danger)"}} onClick={() => setCertFile("")}><I.trash size={12}/> Remove</button>
              </div>
              {!certFile && (
                <div style={{border: "2px dashed var(--border)", borderRadius: 8, padding: "24px 16px", textAlign: "center"}}>
                  <I.upload size={20} style={{color: "var(--text-3)", marginBottom: 8}}/>
                  <div style={{fontWeight: 500, fontSize: 13}}>Upload certificate</div>
                  <div className="muted" style={{fontSize: 12}}>PDF, JPG, or PNG · Max 10 MB</div>
                </div>
              )}
            </div>

            <div className="card card-pad">
              <div style={{fontWeight: 600, fontSize: 14, marginBottom: 14}}>Communication Preferences</div>
              <div style={{display: "flex", alignItems: "center", gap: 14}}>
                <div style={{flex: 1}}>
                  <div style={{fontWeight: 500, fontSize: 13.5}}>Mailing list</div>
                  <div className="muted" style={{fontSize: 12.5}}>Receive product updates, new resources, and practitioner tips</div>
                </div>
                <Toggle on={mailingList} onToggle={() => setMailingList(!mailingList)}/>
              </div>
            </div>
          </div>
        )}

        {section === "support-links" && (
          <div style={{maxWidth: 640}}>
            <h2 style={{fontSize: 18, fontWeight: 700, margin: "0 0 4px"}}>Support</h2>
            <div className="muted" style={{fontSize: 13, marginBottom: 24}}>Help, documentation, and legal</div>

            <div className="card" style={{marginBottom: 16}}>
              {[
                { label: "Help & Support", desc: "Get help with the Vykon platform", icon: <I.headset size={16}/> },
                { label: "Documentation", desc: "API docs and integration guides", icon: <I.book size={16}/> },
                { label: "Terms of Service", desc: "Review our terms", icon: <I.doc size={16}/> },
                { label: "Privacy Policy", desc: "How we handle your data", icon: <I.shield size={16}/> },
              ].map((item, i) => (
                <div key={i} className="row-click" style={{display: "flex", alignItems: "center", gap: 14, padding: "14px 18px", borderBottom: i < 3 ? "1px solid var(--border)" : "none", cursor: "pointer"}}>
                  <span style={{color: "var(--text-3)"}}>{item.icon}</span>
                  <div style={{flex: 1}}>
                    <div style={{fontWeight: 500, fontSize: 13.5}}>{item.label}</div>
                    <div className="muted" style={{fontSize: 12}}>{item.desc}</div>
                  </div>
                  <I.externalLink size={14} style={{color: "var(--text-3)"}}/>
                </div>
              ))}
            </div>

            <div className="card card-pad" style={{borderColor: "var(--danger-container)"}}>
              <div className="row-between">
                <div>
                  <div style={{fontWeight: 600, fontSize: 14, color: "var(--danger)"}}>Delete Account</div>
                  <div className="muted" style={{fontSize: 12.5, marginTop: 2}}>Permanently delete your account and all associated data. This action cannot be undone.</div>
                </div>
                <button className="btn sm" style={{color: "var(--danger)", borderColor: "var(--danger-container)"}} onClick={() => setShowDeleteConfirm(true)}>Delete account</button>
              </div>
              {showDeleteConfirm && (
                <div className="alert danger" style={{marginTop: 14, display: "flex", alignItems: "center", gap: 12}}>
                  <I.warn size={16}/>
                  <div style={{flex: 1, fontSize: 13}}>Are you sure? This will permanently remove all your data.</div>
                  <div className="row" style={{gap: 6}}>
                    <button className="btn sm ghost" onClick={() => setShowDeleteConfirm(false)}>Cancel</button>
                    <button className="btn sm" style={{background: "var(--danger)", color: "#fff", borderColor: "var(--danger)"}}>Confirm delete</button>
                  </div>
                </div>
              )}
            </div>
          </div>
        )}
      </div>

      {showLogoutConfirm && (
        <div className="modal-backdrop" onClick={() => setShowLogoutConfirm(false)}>
          <div className="modal" onClick={e => e.stopPropagation()} style={{maxWidth: 400}}>
            <div className="row" style={{gap: 10, marginBottom: 8}}><I.logout size={18}/><h3 style={{margin: 0}}>Log out?</h3></div>
            <p className="muted" style={{margin: "0 0 20px", fontSize: 13.5}}>You'll need to sign in again to access the practitioner portal.</p>
            <div className="row" style={{justifyContent: "flex-end", gap: 8}}>
              <button className="btn ghost" onClick={() => setShowLogoutConfirm(false)}>Cancel</button>
              <button className="btn primary" onClick={() => setShowLogoutConfirm(false)}>Log out</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { VideoLibrary, ResourceLibrary, EducationPage, SupportServices, NewsPage, PlatformAdminDashboardView, ClinicMemberManagementView, SettingsPage });
