"use client";

import { useEffect, useMemo, useState } from "react";

const pathways = [
  { icon: "◎", title: "Digital product design", meta: "6 skills · 4 weeks", color: "blue" },
  { icon: "↗", title: "Project management", meta: "8 skills · 6 weeks", color: "lime" },
  { icon: "◇", title: "Creative marketing", meta: "5 skills · 3 weeks", color: "orange" },
  { icon: "⌂", title: "Community leadership", meta: "7 skills · 5 weeks", color: "purple" },
];

const roleNavigation = {
  learner: [
    { value: "Home", label: "Home", icon: "⌂" },
    { value: "Store", label: "Course store", icon: "◈" },
    { value: "Learn", label: "My learning", icon: "▤" },
    { value: "Build", label: "My projects", icon: "◆" },
    { value: "Content", label: "Assigned content", icon: "↗" },
    { value: "Portfolio", label: "My portfolio", icon: "▣" },
  ],
  creator: [
    { value: "Organisation", label: "Creator dashboard", icon: "⌂" },
    { value: "Store", label: "Course storefront", icon: "◈" },
    { value: "Content", label: "Connected content", icon: "↗" },
  ],
  admin: [
    { value: "Organisation", label: "Admin dashboard", icon: "⌂" },
    { value: "Reports", label: "Reports & insights", icon: "◫" },
    { value: "Content", label: "Content library", icon: "↗" },
  ],
} as const;

type LearnerState = {
  displayName: string;
  pathway: string;
  projectStarted: number | boolean;
  completedLessons: number;
  portfolioPublished: number | boolean;
  organisationName: string;
  accentColour: string;
  organisationLogoName?: string | null;
  activeRole?: "learner" | "creator" | "admin";
};

export default function Home() {
  const [active, setActive] = useState("Home");
  const [coachOpen, setCoachOpen] = useState(false);
  const [projectStarted, setProjectStarted] = useState(false);
  const [pathway, setPathway] = useState("Project management");
  const [profile, setProfile] = useState<LearnerState | null>(null);
  const [saveStatus, setSaveStatus] = useState("Loading your workspace…");
  const [role, setRole] = useState<"learner" | "creator" | "admin">("learner");
  const [session, setSession] = useState<"checking" | "authenticated" | "anonymous">("checking");
  const [signInUrl, setSignInUrl] = useState("/signin-with-chatgpt?return_to=%2F");
  const [signOutUrl, setSignOutUrl] = useState("/signout-with-chatgpt?return_to=%2F");
  const [environment, setEnvironment] = useState<"test" | "production">("test");

  useEffect(() => {
    async function loadAccount() {
      try {
        const sessionResponse = await fetch("/api/session");
        const sessionData = await sessionResponse.json();
        fetch("/api/environment").then((response) => response.json()).then((data) => setEnvironment(data.environment === "production" ? "production" : "test")).catch(() => undefined);
        setSignInUrl(sessionData.signInUrl ?? "/signin-with-chatgpt?return_to=%2F");
        setSignOutUrl(sessionData.signOutUrl ?? "/signout-with-chatgpt?return_to=%2F");
        if (!sessionData.authenticated) return setSession("anonymous");
        setSession("authenticated");
        const stateResponse = await fetch("/api/state");
        if (!stateResponse.ok) throw new Error("Account state unavailable");
        const data = await stateResponse.json();
        if (!data.state) throw new Error("No learner state");
        setProfile(data.state);
        setProjectStarted(Boolean(data.state.projectStarted));
        setPathway(data.state.pathway);
        const savedRole = data.state.activeRole ?? "learner";
        setRole(savedRole);
        if (savedRole !== "learner") setActive("Organisation");
        setSaveStatus("All progress saved");
      } catch {
        setSession("anonymous");
        setSaveStatus("Sign in required");
      }
    }
    loadAccount();
  }, []);

  async function save(changes: Record<string, unknown>) {
    setSaveStatus("Saving…");
    try {
      const response = await fetch("/api/state", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(changes),
      });
      const data = await response.json();
      if (data.state) setProfile(data.state);
      setSaveStatus("All progress saved");
    } catch {
      setSaveStatus("Saved for this session");
    }
  }

  const pageTitle = useMemo(() => {
    if (active === "Home") return `Good afternoon, ${profile?.displayName?.split(" ")[0] ?? "Maya"}`;
    if (active === "Organisation") return role === "creator" ? "Creator dashboard" : "Organisation dashboard";
    return roleNavigation[role].find((item) => item.value === active)?.label ?? active;
  }, [active, profile, role]);

  function changeRole(nextRole: "learner" | "creator" | "admin") {
    setRole(nextRole);
    setActive(nextRole === "learner" ? "Home" : "Organisation");
  }

  if (session === "checking") return <LoadingGate />;
  if (session === "anonymous") return <SignInGate signInUrl={signInUrl} />;

  return (
    <main className="app-shell">
      <aside className="sidebar">
        <div className="brand"><img src="/connectpoint-logo.png" alt="ConnectPoint" /></div>
        <nav aria-label="Main navigation">
          {roleNavigation[role].map((item) => (
            <button key={item.value} className={active === item.value ? "nav-item active" : "nav-item"} onClick={() => setActive(item.value)}>
              <span className="nav-icon">{item.icon}</span>
              {item.label}
            </button>
          ))}
        </nav>
        <div className="nav-divider" />
        {role === "learner" && <button className="nav-item"><span className="nav-icon">◫</span>Explore skills</button>}
        <button className="nav-item"><span className="nav-icon">⚙</span>Settings</button>
        <div className="sidebar-card">
          <div className="spark">✦</div>
          <strong>{role === "learner" ? "Learning that leads somewhere." : role === "creator" ? "Create learning that proves capability." : "One platform. Your organisation."}</strong>
          <p>{role === "learner" ? "Every pathway ends with something real you can show." : role === "creator" ? "Build, publish and monetise practical courses." : "Manage learning, reporting and your white-label experience."}</p>
        </div>
        <div className="user-row">
          <div className="avatar">MP</div><div><strong>{profile?.displayName ?? "Maya Patel"}</strong><small>{role === "learner" ? "Learner" : role === "creator" ? "Course creator" : "Organisation admin"} · {saveStatus}</small></div><a className="signout-link" href={signOutUrl}>Sign out</a>
        </div>
      </aside>

      <section className="main-content">
        <header className="topbar">
          <div><span className="eyebrow">{role === "learner" ? "YOUR LEARNING SPACE" : role === "creator" ? "CREATOR WORKSPACE" : "ADMINISTRATION SPACE"} {environment === "test" && <b className="environment-badge">TEST ENVIRONMENT</b>}</span><h1>{pageTitle}</h1></div>
          <div className="top-actions">
            {profile?.activeRole === "admin" && <label className="role-switcher" title="Available to organisation administrators only"><span>SWITCH WORKSPACE</span><select aria-label="Switch workspace role" value={role} onChange={(event) => changeRole(event.target.value as "learner" | "creator" | "admin")}><option value="admin">Admin dashboard</option><option value="creator">Creator dashboard</option><option value="learner">Learner dashboard</option></select></label>}
            <button className="icon-button" aria-label="Notifications">♢<i /></button>
            {role === "learner" && <button className="coach-button" onClick={() => setCoachOpen(!coachOpen)}>✦ Ask your coach</button>}
          </div>
        </header>

        {active === "Home" ? (
          <>
            <section className="hero-card">
              <div className="hero-copy">
                <span className="status-pill"><b /> YOUR NEXT BEST STEP</span>
                <h2>Turn your project plan<br />into something real.</h2>
                <p>You’ve learned the foundations. Now apply them to a community event brief and build evidence for your portfolio.</p>
                <div className="hero-actions">
                  <button className="primary" onClick={() => { setProjectStarted(true); save({ projectStarted: true }); setActive("Build"); }}>Start building <span>→</span></button>
                  <button className="text-button" onClick={() => setActive("Learn")}>Review what I’ve learned</button>
                </div>
              </div>
              <div className="progress-orbit">
                <div className="orbit-ring"><div className="orbit-inner"><strong>68%</strong><span>pathway<br />complete</span></div></div>
                <div className="orbit-tag tag-one">✓ 4 skills verified</div>
                <div className="orbit-tag tag-two">◆ 1 project next</div>
              </div>
            </section>

            <section className="stats-grid">
              <div className="stat"><span className="stat-icon blue">↗</span><div><small>SKILLS GROWING</small><strong>7</strong><p>+2 this month</p></div></div>
              <div className="stat"><span className="stat-icon lime">◆</span><div><small>PROJECTS BUILT</small><strong>2</strong><p>1 ready to publish</p></div></div>
              <div className="stat"><span className="stat-icon purple">⌁</span><div><small>LEARNING STREAK</small><strong>12 <em>days</em></strong><p>Personal best</p></div></div>
            </section>

            <section className="content-grid">
              <div className="panel current-path">
                <div className="section-heading"><div><span className="eyebrow">CURRENT PATHWAY</span><h3>{pathway}</h3></div><button onClick={() => setActive("Learn")}>View pathway →</button></div>
                <div className="timeline">
                  <div className="timeline-item done"><span>✓</span><div><small>COMPLETED</small><strong>Foundations of project planning</strong><p>Scope, outcomes and stakeholders</p></div><b>100%</b></div>
                  <div className="timeline-item current"><span>2</span><div><small>IN PROGRESS</small><strong>Budgets, risks and resources</strong><p>3 of 5 lessons complete</p><div className="mini-progress"><i /></div></div><b>60%</b></div>
                  <div className="timeline-item locked"><span>3</span><div><small>UP NEXT</small><strong>Deliver your community project</strong><p>Unlocks after this module</p></div><b>⌕</b></div>
                </div>
              </div>
              <div className="panel coach-panel">
                <div className="coach-head"><span>✦</span><div><small>YOUR AI COACH</small><strong>A recommendation for you</strong></div></div>
                <blockquote>“You’re strong at planning and communication. Building a live event will help you prove budgeting and risk management next.”</blockquote>
                <div className="recommendation"><div className="rec-icon">◆</div><div><small>RECOMMENDED PROJECT</small><strong>Plan a community pop-up event</strong><p>Builds 3 skills · About 6 hours</p></div></div>
                <button className="outline-button" onClick={() => setCoachOpen(true)}>Why this recommendation?</button>
              </div>
            </section>

            <section className="explore-section">
              <div className="section-heading"><div><span className="eyebrow">EXPLORE WHAT’S POSSIBLE</span><h3>Build skills that lead to real work.</h3></div><button>Browse all pathways →</button></div>
              <div className="pathway-grid">
                {pathways.map((p) => <button key={p.title} className="pathway-card" onClick={() => { setPathway(p.title); save({ pathway: p.title }); }}><span className={`path-icon ${p.color}`}>{p.icon}</span><strong>{p.title}</strong><small>{p.meta}</small><i>→</i></button>)}
              </div>
            </section>
          </>
        ) : (
          <WorkspaceView active={active} projectStarted={projectStarted} profile={profile} role={role} onNavigate={setActive} onSave={save} />
        )}
      </section>

      {coachOpen && <div className="coach-drawer" role="dialog" aria-label="AI learning coach"><button className="close" onClick={() => setCoachOpen(false)}>×</button><span className="ai-mark">✦</span><small>CONNECTPOINT COACH</small><h2>Let’s turn learning into evidence.</h2><p>Based on your recent work, the best next step is to practise budgeting in a real project. I’ll guide you, but the decisions stay yours.</p><div className="prompt-chip">How should I begin the event budget?</div><div className="prompt-chip">Show me the skills I’ll prove</div><textarea placeholder="Ask about your next step…" aria-label="Message your coach" /><button className="primary full">Send message →</button></div>}
    </main>
  );
}

function LoadingGate() {
  return <main className="auth-shell"><div className="auth-card"><img src="/connectpoint-logo.png" alt="ConnectPoint" /><div className="auth-spinner" /><h1>Opening your learning workspace…</h1><p>We’re confirming your secure session.</p></div></main>;
}

function SignInGate({ signInUrl }: { signInUrl: string }) {
  return <main className="auth-shell"><div className="auth-card"><img src="/connectpoint-logo.png" alt="ConnectPoint" /><span className="eyebrow">SECURE ACCOUNT ACCESS</span><h1>Learn. Build. Prove.</h1><p>Sign in to access your assigned learner, creator or organisation workspace. Your role is checked on the server before protected tools are opened.</p><a className="auth-primary" href={signInUrl}>Continue securely →</a><div className="auth-trust"><span>✓ Secure managed sign-in</span><span>✓ Role-protected workspace</span><span>✓ No password stored by ConnectPoint</span></div></div></main>;
}

function WorkspaceView({ active, projectStarted, profile, role, onNavigate, onSave }: { active: string; projectStarted: boolean; profile: LearnerState | null; role: "learner" | "creator" | "admin"; onNavigate: (v: string) => void; onSave: (v: Record<string, unknown>) => void }) {
  const copy: Record<string, { kicker: string; title: string; body: string }> = {
    Learn: { kicker: "YOUR PATHWAY", title: "Project management", body: "Short lessons, practical exercises and feedback designed around the work you want to do." },
    Store: { kicker: "CONNECTPOINT COURSE STORE", title: "Learn something. Build something.", body: "Practical courses from trusted experts, each ending with a real project you can add to your portfolio." },
    Build: { kicker: projectStarted ? "PROJECT STARTED" : "PRACTICAL PROJECT", title: "Plan a community pop-up event", body: "Create a scope, budget and risk register. Each milestone becomes verified evidence of your skills." },
    Content: { kicker: role === "learner" ? "CONNECTED LEARNING" : "INTEROPERABILITY HUB", title: role === "learner" ? "Your hosted learning library" : "SCORM, AICC and connected content", body: role === "learner" ? "Launch assigned learning from one place while ConnectPoint records your activity." : "Host standards-based packages and connect externally managed courses without rebuilding them." },
    Reports: { kicker: "ORGANISATION INTELLIGENCE", title: "Learning impact at a glance", body: "Monitor engagement, completions, practical projects and learner confidence from one live reporting view." },
    Portfolio: { kicker: "YOUR PROOF OF EXPERIENCE", title: "Work worth showing", body: "Publish finished projects, verified skills and outcome-focused CV statements in one place." },
    Organisation: role === "creator"
      ? { kicker: "CREATOR WORKSPACE", title: "Build and sell practical learning", body: "Create courses, add video from anywhere and turn every learning journey into a portfolio-ready project." }
      : { kicker: "WHITE-LABEL CONTROL", title: profile?.organisationName ?? "ConnectPoint Learning", body: "Give every partner organisation its own identity while keeping one robust learning platform underneath." },
  };
  const c = copy[active] || copy.Learn;
  return <div className="workspace-page">
    <div className="workspace-intro"><span className="eyebrow">{c.kicker}</span><h2>{c.title}</h2><p>{c.body}</p></div>
    {active === "Store" ? <CourseStore onNavigate={onNavigate} /> : active === "Reports" ? <AnalyticsDashboard /> : active === "Content" ? <ContentHub role={role} /> : active === "Organisation" ? <OrganisationPanel profile={profile} role={role} onSave={onSave} /> : <div className="workspace-grid">
      <div className="panel large-work-card">
        <span className="status-pill"><b /> {active === "Portfolio" ? "VERIFIED EVIDENCE" : "CURRENT FOCUS"}</span>
        <h3>{active === "Learn" ? "Budgets, risks and resources" : active === "Build" ? "Milestone 1 — Define the brief" : "Community pop-up event plan"}</h3>
        <p>{active === "Learn" ? "Learn how to estimate costs, prepare contingencies and make informed trade-offs." : active === "Build" ? "Describe the audience, desired outcome, constraints and measures of success." : "Demonstrated project planning, budgeting and stakeholder communication."}</p>
        <div className="task-list"><span>✓ Understand the goal</span><span>✓ Review an example</span><span>{active === "Portfolio" ? "✓ Assessed against rubric" : "○ Complete the practical task"}</span></div>
        <button className="primary" onClick={() => { if (active === "Portfolio") onSave({ portfolioPublished: true }); onNavigate(active === "Learn" ? "Build" : "Portfolio"); }}>{active === "Learn" ? "Continue lesson" : active === "Build" ? "Open project workspace" : profile?.portfolioPublished ? "View published portfolio" : "Publish portfolio"} →</button>
      </div>
      <div className="panel evidence-card"><span className="stat-icon lime">↗</span><small>SKILLS IN THIS STEP</small><h3>What you’ll prove</h3><div className="skill-chip">Project planning <b>Advanced</b></div><div className="skill-chip">Budgeting <b>Growing</b></div><div className="skill-chip">Communication <b>Verified</b></div></div>
      {active === "Learn" && <AssessmentCard />}
      {active === "Learn" && <FeedbackSurvey />}
      {active === "Build" && <EvidenceSubmission />}
      {active === "Portfolio" && <EvidencePortfolio />}
    </div>}
  </div>;
}

type AnalyticsPerson = {
  email: string;
  displayName: string;
  pathway: string;
  completedLessons: number;
  projectStarted: number;
  portfolioPublished: number;
  projects: number;
  completions: number;
  status: string;
};

function AnalyticsDashboard() {
  const [summary, setSummary] = useState<Record<string, number> | null>(null);
  const [people, setPeople] = useState<AnalyticsPerson[]>([]);
  const [status, setStatus] = useState("Loading live organisation data…");
  const [period, setPeriod] = useState("30");

  async function loadReport(nextPeriod = period) {
    setStatus("Generating report…");
    fetch(`/api/analytics?period=${nextPeriod}`).then(async (response) => {
      const data = await response.json();
      if (!response.ok) throw new Error(data.error);
      setSummary(data.summary);
      setPeople(data.people ?? []);
      setStatus(`Report generated from ${data.summary?.learners ?? 0} learner records`);
    }).catch(() => setStatus("Reporting data is temporarily unavailable"));
  }

  useEffect(() => { loadReport("30"); }, []);

  const completionRate = summary?.completionRate ?? 0;
  const projectRate = summary?.projectAssessmentRate ?? 0;
  const attention = people.filter((person) => !person.projectStarted || person.completedLessons < 3).length;

  return <div className="analytics-dashboard">
    <div className="report-toolbar panel">
      <div><span className="eyebrow">REPORT GENERATOR</span><strong>Learning impact report</strong><small>{status}</small></div>
      <label>Reporting period<select value={period} onChange={(event) => setPeriod(event.target.value)}><option value="7">Last 7 days</option><option value="30">Last 30 days</option><option value="90">Last 90 days</option><option value="all">All time</option></select></label>
      <button className="outline-button" onClick={() => loadReport()}>Generate report</button>
      <a className="report-export" href={`/api/analytics?format=csv&period=${period}`}>Export CSV</a>
      <button className="primary" onClick={() => window.print()}>Print / Save PDF</button>
    </div>
    <div className="analytics-summary">
      <div><span className="analytics-icon blue">◎</span><small>TOTAL LEARNERS</small><strong>{summary?.learners ?? "—"}</strong><p>{summary?.activeLearners ?? 0} active in period</p></div>
      <div><span className="analytics-icon lime">✓</span><small>CONTENT COMPLETION</small><strong>{completionRate}%</strong><p>{summary?.completions ?? 0} completed launches</p></div>
      <div><span className="analytics-icon purple">◆</span><small>PRACTICAL PROJECTS</small><strong>{summary?.projects ?? "—"}</strong><p>{projectRate}% assessed</p></div>
      <div><span className="analytics-icon orange">✦</span><small>NEEDS ATTENTION</small><strong>{attention}</strong><p>Low progress or no project</p></div>
    </div>

    <div className="analytics-grid">
      <div className="panel impact-panel">
        <span className="eyebrow">LEARN → BUILD → PROVE</span>
        <h3>Outcome pipeline</h3>
        <div className="impact-stage"><div><span>1</span><strong>Learning activity</strong><small>{summary?.completedLessons ?? 0} lessons completed</small></div><b style={{ width: `${Math.min(100, (summary?.completedLessons ?? 0) * 8)}%` }} /></div>
        <div className="impact-stage"><div><span>2</span><strong>Projects submitted</strong><small>{summary?.projects ?? 0} pieces of practical evidence</small></div><b style={{ width: `${Math.min(100, (summary?.projects ?? 0) * 15)}%` }} /></div>
        <div className="impact-stage"><div><span>3</span><strong>Projects assessed</strong><small>{summary?.assessedProjects ?? 0} verified outcomes</small></div><b style={{ width: `${projectRate}%` }} /></div>
      </div>
      <div className="panel sentiment-panel">
        <span className="eyebrow">LEARNER FEEDBACK</span>
        <h3>Experience and confidence</h3>
        <div className="sentiment-score"><strong>{summary?.courseRating ? summary.courseRating.toFixed(1) : "—"}</strong><span>Course rating<small>out of 5</small></span></div>
        <div className="sentiment-score"><strong>{summary?.confidence ? summary.confidence.toFixed(1) : "—"}</strong><span>Confidence after learning<small>out of 5</small></span></div>
        <p>Based on {summary?.feedback ?? 0} feedback responses.</p>
      </div>
    </div>

    <div className="panel learner-monitor">
      <div className="member-heading"><div><span className="eyebrow">LEARNER MONITOR</span><h3>Progress requiring action</h3><p>Use learning and project signals to identify where support will have the greatest impact.</p></div><span className="secure-pill">Live saved records</span></div>
      <div className="learner-table-head"><span>Learner</span><span>Pathway</span><span>Lessons</span><span>Projects</span><span>Portfolio</span><span>Signal</span></div>
      {people.map((person) => {
        const needsAttention = !person.projectStarted || person.completedLessons < 3;
        return <div className="learner-table-row" key={person.email}>
          <div><span className="member-avatar">{(person.displayName || person.email)[0].toUpperCase()}</span><span><strong>{person.displayName || person.email.split("@")[0]}</strong><small>{person.email}</small></span></div>
          <span>{person.pathway}</span><b>{person.completedLessons}</b><b>{person.projects}</b>
          <span>{person.portfolioPublished ? "Published" : "Not yet"}</span>
          <em className={needsAttention ? "attention" : "on-track"}>{needsAttention ? "Support next" : "On track"}</em>
        </div>;
      })}
      {!people.length && <div className="empty-member">Learner progress will appear here as people begin using the platform.</div>}
      <small className="save-note">{status}</small>
    </div>
  </div>;
}

function OrganisationPanel({ profile, role, onSave }: { profile: LearnerState | null; role: "learner" | "creator" | "admin"; onSave: (v: Record<string, unknown>) => void }) {
  const [name, setName] = useState(profile?.organisationName ?? "ConnectPoint Learning");
  const [colour, setColour] = useState(profile?.accentColour ?? "#08a9df");
  const [programmes, setProgrammes] = useState<Array<{ id: number; title: string; audience: string; skill: string; status: string }>>([]);
  const [title, setTitle] = useState("");
  const [audience, setAudience] = useState("");
  const [skill, setSkill] = useState("");
  const [programmeStatus, setProgrammeStatus] = useState("Loading programmes…");
  const [logo, setLogo] = useState<File | null>(null);
  const [logoUrl, setLogoUrl] = useState<string | null>(null);
  useEffect(() => {
    if (profile) {
      setName(profile.organisationName);
      setColour(profile.accentColour);
    }
  }, [profile]);
  useEffect(() => {
    fetch("/api/programmes").then((response) => response.json()).then((data) => {
      setProgrammes(data.programmes ?? []);
      setProgrammeStatus(`${data.programmes?.length ?? 0} programmes`);
    }).catch(() => setProgrammeStatus("Programme service unavailable"));
    fetch("/api/branding").then((response) => response.json()).then((data) => setLogoUrl(data.logoUrl ? `${data.logoUrl}&v=${Date.now()}` : null)).catch(() => undefined);
  }, []);

  async function createProgramme() {
    if (!title || !audience || !skill) return setProgrammeStatus("Complete all three fields");
    setProgrammeStatus("Creating…");
    const response = await fetch("/api/programmes", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ title, audience, skill }),
    });
    const data = await response.json();
    if (data.programmes) {
      setProgrammes(data.programmes);
      setTitle(""); setAudience(""); setSkill("");
      setProgrammeStatus("Draft programme created");
    } else {
      setProgrammeStatus(data.error ?? "Could not create programme");
    }
  }

  async function uploadLogo() {
    if (!logo) return setProgrammeStatus("Choose a logo image first");
    setProgrammeStatus("Uploading organisation logo…");
    const form = new FormData();
    form.set("logo", logo);
    const response = await fetch("/api/branding", { method: "POST", body: form });
    const data = await response.json();
    if (!response.ok) return setProgrammeStatus(data.error ?? "Could not upload logo");
    setLogoUrl(`${data.logoUrl}&v=${Date.now()}`);
    setProgrammeStatus("Organisation logo updated");
  }

  return <>
    <div className="role-banner"><span>{role === "creator" ? "✦" : "⌂"}</span><div><small>{role === "creator" ? "COURSE CREATOR" : "ORGANISATION ADMIN"}</small><strong>{role === "creator" ? "Your creator business" : "Your organisation workspace"}</strong><p>{role === "creator" ? "Create, publish and monetise courses that end in real work." : "Manage programmes, learners and your white-label experience."}</p></div></div>
    {role === "creator" && <CommerceMetrics />}
    {role === "admin" && <div className="admin-summary">
      <div><small>PROGRAMMES</small><strong>{programmes.length}</strong></div>
      <div><small>PUBLISHED</small><strong>{programmes.filter((p) => p.status === "published").length}</strong></div>
      <div><small>LEARNERS</small><strong>128</strong></div>
      <div><small>PROJECTS SUBMITTED</small><strong>42</strong></div>
    </div>}
    {role === "admin" && <MemberManagement />}
    <div className="workspace-grid">
      {role === "admin" && <div className="panel large-work-card">
        <span className="status-pill"><b /> PROGRAMME BUILDER</span>
        <h3>Create a learning programme</h3>
        <p>Define the audience and skill outcome first. Lessons, assessment and a practical project will sit underneath this programme.</p>
        <label className="form-field">Programme title<input value={title} onChange={(event) => setTitle(event.target.value)} placeholder="e.g. Digital Marketing Foundations" /></label>
        <label className="form-field">Who is it for?<input value={audience} onChange={(event) => setAudience(event.target.value)} placeholder="e.g. Small business owners" /></label>
        <label className="form-field">Primary skill<input value={skill} onChange={(event) => setSkill(event.target.value)} placeholder="e.g. Campaign planning" /></label>
        <button className="primary" onClick={createProgramme}>Create draft programme →</button>
        <small className="save-note">{programmeStatus}</small>
      </div>}
      {role === "admin" && <div className="panel programme-list">
        <span className="eyebrow">PROGRAMME LIBRARY</span>
        <h3>Learning catalogue</h3>
        {programmes.map((programme) => <div className="programme-row" key={programme.id}><div><strong>{programme.title}</strong><small>{programme.audience}</small><span>{programme.skill}</span></div><b className={programme.status}>{programme.status}</b></div>)}
      </div>}
      {role === "admin" && <div className="panel brand-settings">
        <span className="eyebrow">WHITE-LABEL BRAND</span>
        <div className="brand-logo-preview">{logoUrl ? <img src={logoUrl} alt={`${name} logo`} /> : <img src="/connectpoint-logo.png" alt="Current organisation logo" />}</div>
        <label className="form-field">Organisation name<input value={name} onChange={(event) => setName(event.target.value)} /></label>
        <label className="form-field">Brand accent<div className="colour-row"><input type="color" value={colour} onChange={(event) => setColour(event.target.value)} /><code>{colour}</code></div></label>
        <label className="form-field">Organisation logo<input className="file-input" type="file" accept=".png,.jpg,.jpeg,.webp" onChange={(event) => setLogo(event.target.files?.[0] ?? null)} /></label>
        <button className="outline-button" onClick={uploadLogo}>Upload logo</button>
        <button className="outline-button" onClick={() => onSave({ organisationName: name, accentColour: colour })}>Save brand settings</button>
      </div>}
    </div>
    {role === "creator" && <CourseStudio />}
    <ContentHub role={role} />
  </>;
}

type OrganisationMember = {
  id: number;
  email: string;
  displayName?: string | null;
  role: "learner" | "creator" | "admin";
  status: "invited" | "active" | "suspended";
};

function MemberManagement() {
  const [members, setMembers] = useState<OrganisationMember[]>([]);
  const [email, setEmail] = useState("");
  const [role, setRole] = useState<OrganisationMember["role"]>("learner");
  const [status, setStatus] = useState("Loading people…");

  useEffect(() => {
    fetch("/api/members").then((response) => response.json()).then((data) => {
      setMembers(data.members ?? []);
      setStatus(`${data.members?.length ?? 0} people in this workspace`);
    }).catch(() => setStatus("People service unavailable"));
  }, []);

  async function invite() {
    if (!email.trim()) return setStatus("Enter an email address");
    setStatus("Adding person…");
    const response = await fetch("/api/members", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ action: "invite", email, role }),
    });
    const data = await response.json();
    if (!response.ok) return setStatus(data.error ?? "Could not add person");
    setMembers(data.members ?? []);
    setEmail("");
    setStatus("Access prepared. They can now sign in with that email.");
  }

  async function update(member: OrganisationMember, changes: Partial<Pick<OrganisationMember, "role" | "status">>) {
    setStatus(`Updating ${member.email}…`);
    const response = await fetch("/api/members", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ action: "update", id: member.id, ...changes }),
    });
    const data = await response.json();
    if (!response.ok) return setStatus(data.error ?? "Could not update access");
    setMembers(data.members ?? []);
    setStatus("Workspace access updated");
  }

  return <div className="panel member-management">
    <div className="member-heading">
      <div><span className="eyebrow">PEOPLE & ACCESS</span><h3>Invite and assign roles</h3><p>Prepare access using a person’s sign-in email. Their assigned workspace activates automatically when they sign in.</p></div>
      <span className="secure-pill">Server-protected roles</span>
    </div>
    <div className="member-invite">
      <label className="form-field">Email address<input type="email" value={email} onChange={(event) => setEmail(event.target.value)} placeholder="person@organisation.com" /></label>
      <label className="form-field">Workspace role<select value={role} onChange={(event) => setRole(event.target.value as OrganisationMember["role"])}><option value="learner">Learner</option><option value="creator">Content creator</option><option value="admin">Administrator</option></select></label>
      <button className="primary" onClick={invite}>Prepare access →</button>
    </div>
    <div className="member-list">
      {members.length === 0 ? <div className="empty-member">No additional people yet. Add the first learner or creator above.</div> : members.map((member) => <div className="member-row" key={member.id}>
        <div className="member-avatar">{(member.displayName || member.email).slice(0, 1).toUpperCase()}</div>
        <div className="member-identity"><strong>{member.displayName || member.email.split("@")[0]}</strong><small>{member.email}</small></div>
        <select aria-label={`Role for ${member.email}`} value={member.role} onChange={(event) => update(member, { role: event.target.value as OrganisationMember["role"] })}><option value="learner">Learner</option><option value="creator">Creator</option><option value="admin">Admin</option></select>
        <select aria-label={`Status for ${member.email}`} className={`member-status ${member.status}`} value={member.status} onChange={(event) => update(member, { status: event.target.value as OrganisationMember["status"] })}><option value="invited">Invited</option><option value="active">Active</option><option value="suspended">Suspended</option></select>
      </div>)}
    </div>
    <small className="save-note">{status}</small>
  </div>;
}

type CourseProduct = {
  id: number;
  title: string;
  description: string;
  category: string;
  outcome: string;
  projectTitle: string;
  lessonCount: number;
  pricePence: number;
  enrolled: number;
};

function CourseStore({ onNavigate }: { onNavigate: (v: string) => void }) {
  const [products, setProducts] = useState<CourseProduct[]>([]);
  const [selected, setSelected] = useState<CourseProduct | null>(null);
  const [status, setStatus] = useState("Loading courses…");

  async function load() {
    const response = await fetch("/api/commerce");
    const data = await response.json();
    setProducts(data.products ?? []);
    setStatus(`${data.products?.length ?? 0} practical courses`);
  }
  useEffect(() => { load().catch(() => setStatus("Course store unavailable")); }, []);

  async function enrol(product: CourseProduct) {
    setStatus("Creating your demo enrolment…");
    await fetch("/api/commerce", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ action: "enrol", productId: product.id }),
    });
    await load();
    setSelected(null);
    setStatus("Enrolled — your course is ready");
  }

  return <div className="storefront">
    <div className="store-toolbar"><div><strong>Outcome-led courses</strong><small>{status}</small></div><div className="store-filter"><button className="active">All</button><button>Business</button><button>Creative</button><button>Marketing</button></div></div>
    <div className="course-grid">
      {products.map((course, index) => <article className="course-card" key={course.id}>
        <div className={`course-cover cover-${index + 1}`}><span>{course.category}</span><strong>{course.projectTitle}</strong><small>REAL-WORLD PROJECT</small></div>
        <div className="course-body"><small>{course.lessonCount} LESSONS · PROJECT INCLUDED</small><h3>{course.title}</h3><p>{course.description}</p><div className="course-outcome"><b>↗</b><span><small>YOU WILL BUILD</small>{course.outcome}</span></div><div className="course-footer"><strong>£{(course.pricePence / 100).toFixed(0)}</strong>{course.enrolled ? <button className="enrolled" onClick={() => onNavigate("Learn")}>Continue learning →</button> : <button onClick={() => setSelected(course)}>View course →</button>}</div></div>
      </article>)}
    </div>
    {selected && <div className="checkout-overlay" role="dialog" aria-label="Course checkout preview"><div className="checkout-card"><button className="close" onClick={() => setSelected(null)}>×</button><span className="eyebrow">CHECKOUT PREVIEW</span><h2>{selected.title}</h2><p>{selected.description}</p><div className="checkout-line"><span>Course access</span><strong>£{(selected.pricePence / 100).toFixed(2)}</strong></div><div className="checkout-line"><span>Platform fee</span><strong>£0.00</strong></div><div className="checkout-total"><span>Total</span><strong>£{(selected.pricePence / 100).toFixed(2)}</strong></div><div className="demo-notice">This is a demonstration checkout. No payment will be taken.</div><button className="primary full" onClick={() => enrol(selected)}>Complete demo enrolment →</button></div></div>}
  </div>;
}

function CommerceMetrics() {
  const [metrics, setMetrics] = useState<{ sales: number; revenuePence: number; learners: number } | null>(null);
  useEffect(() => {
    fetch("/api/commerce").then((response) => response.json()).then((data) => setMetrics(data.metrics ?? null)).catch(() => undefined);
  }, []);
  return <div className="commerce-banner"><div><span>£</span><div><small>CREATOR COMMERCE</small><strong>Sell learning that leads to evidence.</strong></div></div><div className="commerce-numbers"><span><b>£{((metrics?.revenuePence ?? 0) / 100).toFixed(0)}</b>Demo revenue</span><span><b>{metrics?.sales ?? 0}</b>Enrolments</span><span><b>{metrics?.learners ?? 0}</b>Learners</span></div></div>;
}

type StudioModule = { id: number; title: string; position: number; lessonCount: number; durationMinutes: number };
type StudioLesson = { id: number; moduleId: number; title: string; lessonType: string; summary: string; mediaName: string | null; mediaUrl: string | null; durationMinutes: number; status: string };

function CourseStudio() {
  const [modules, setModules] = useState<StudioModule[]>([]);
  const [lessons, setLessons] = useState<StudioLesson[]>([]);
  const [moduleId, setModuleId] = useState(0);
  const [title, setTitle] = useState("");
  const [summary, setSummary] = useState("");
  const [type, setType] = useState("video");
  const [duration, setDuration] = useState(5);
  const [media, setMedia] = useState<File | null>(null);
  const [mediaUrl, setMediaUrl] = useState("");
  const [status, setStatus] = useState("Loading course structure…");

  async function load() {
    const response = await fetch("/api/studio");
    const data = await response.json();
    setModules(data.modules ?? []);
    setLessons(data.lessons ?? []);
    if (!moduleId && data.modules?.[0]) setModuleId(data.modules[0].id);
    setStatus(`${data.lessons?.length ?? 0} lessons · ${(data.modules ?? []).reduce((sum: number, item: StudioModule) => sum + Number(item.durationMinutes), 0)} minutes`);
  }
  useEffect(() => { load().catch(() => setStatus("Course studio unavailable")); }, []);

  async function addLesson() {
    setStatus("Saving lesson…");
    const form = new FormData();
    form.set("moduleId", String(moduleId));
    form.set("title", title);
    form.set("summary", summary);
    form.set("lessonType", type);
    form.set("durationMinutes", String(duration));
    form.set("mediaUrl", mediaUrl);
    if (media) form.set("media", media);
    const response = await fetch("/api/studio", { method: "POST", body: form });
    const data = await response.json();
    if (!response.ok) return setStatus(data.error ?? "Could not save lesson");
    setModules(data.modules ?? []);
    setLessons(data.lessons ?? []);
    setTitle(""); setSummary(""); setMedia(null); setMediaUrl("");
    setStatus("Draft lesson saved");
  }

  function exportScorm(format: "scorm12" | "scorm2004") {
    setStatus(`Building ${format === "scorm2004" ? "SCORM 2004" : "SCORM 1.2"} package…`);
    window.location.href = `/api/scorm-export?format=${format}`;
    window.setTimeout(() => setStatus("SCORM package exported"), 1200);
  }

  return <section className="studio panel">
    <div className="studio-header"><div><span className="eyebrow">COURSE STUDIO · BUILT-IN SCORM AUTHORING</span><h3>Community Project Management</h3><p>Write lessons, add activities and media, then export a standards-ready SCORM package.</p></div><div className="studio-actions"><span className="secure-pill">● Draft changes saved</span><small>{status}</small><div><button className="outline-button" onClick={() => exportScorm("scorm12")}>Export SCORM 1.2</button><button className="outline-button" onClick={() => exportScorm("scorm2004")}>Export SCORM 2004</button></div></div></div>
    <div className="studio-layout">
      <div className="curriculum">
        {modules.map((module) => <div className="module-block" key={module.id}><div className="module-title"><span>{module.position}</span><div><strong>{module.title}</strong><small>{module.lessonCount} lessons · {module.durationMinutes} min</small></div></div>
          {lessons.filter((lesson) => lesson.moduleId === module.id).map((lesson) => <button className="lesson-row" key={lesson.id} onClick={() => lesson.mediaUrl && window.open(lesson.mediaUrl, "_blank", "noopener,noreferrer")}><span>{lesson.lessonType === "video" ? "▶" : lesson.lessonType === "resource" ? "▤" : "✓"}</span><div><strong>{lesson.title}</strong><small>{lesson.durationMinutes} min {lesson.mediaName ? `· ${lesson.mediaName}` : lesson.mediaUrl ? "· linked video" : ""}</small></div><b className={lesson.status}>{lesson.status}</b></button>)}
        </div>)}
      </div>
      <div className="lesson-editor">
        <span className="eyebrow">ADD LESSON</span>
        <label className="form-field">Module<select value={moduleId} onChange={(event) => setModuleId(Number(event.target.value))}>{modules.map((module) => <option value={module.id} key={module.id}>{module.title}</option>)}</select></label>
        <label className="form-field">Lesson title<input value={title} onChange={(event) => setTitle(event.target.value)} placeholder="e.g. Build your project budget" /></label>
        <div className="editor-pair"><label className="form-field">Type<select value={type} onChange={(event) => setType(event.target.value)}><option value="video">Video</option><option value="activity">Activity</option><option value="resource">Resource</option></select></label><label className="form-field">Minutes<input type="number" min="1" max="180" value={duration} onChange={(event) => setDuration(Number(event.target.value))} /></label></div>
        <label className="form-field">Lesson summary<textarea value={summary} onChange={(event) => setSummary(event.target.value)} placeholder="What will the learner understand or do?" /></label>
        <div className="media-divider"><span>LINK OR UPLOAD</span></div>
        <label className="form-field">YouTube, Vimeo or other video link<input type="url" value={mediaUrl} onChange={(event) => setMediaUrl(event.target.value)} placeholder="https://youtube.com/watch?v=…" /></label>
        <label className="media-drop"><input type="file" accept=".mp4,.webm,.pdf,.png,.jpg,.jpeg" onChange={(event) => setMedia(event.target.files?.[0] ?? null)} /><span>↑</span><strong>{media?.name ?? "Add lesson media"}</strong><small>Video, PDF or image · up to 50 MB in this prototype</small></label>
        <button className="primary full" onClick={addLesson}>Save draft lesson →</button>
      </div>
    </div>
  </section>;
}

type TrainingItem = {
  id: number;
  title: string;
  format: "scorm12" | "scorm2004" | "aicc";
  launchUrl: string | null;
  packageName: string | null;
  launchPath?: string | null;
  status: string;
  launches: number;
  completed?: number;
  bestScore?: number | null;
  totalSeconds?: number;
};

function ContentHub({ role }: { role: "learner" | "creator" | "admin" }) {
  const [items, setItems] = useState<TrainingItem[]>([]);
  const [title, setTitle] = useState("");
  const [format, setFormat] = useState<TrainingItem["format"]>("scorm12");
  const [launchUrl, setLaunchUrl] = useState("");
  const [file, setFile] = useState<File | null>(null);
  const [status, setStatus] = useState("Loading connected content…");
  const [survey, setSurvey] = useState<{ responses: number; averageRating: number | null; averageConfidence: number | null } | null>(null);

  async function load() {
    const response = await fetch("/api/content");
    const data = await response.json();
    setItems(data.items ?? []);
    setSurvey(data.survey ?? null);
    setStatus(`${data.items?.length ?? 0} hosted items`);
  }
  useEffect(() => { load().catch(() => setStatus("Content library unavailable")); }, []);

  async function addContent() {
    const form = new FormData();
    form.set("title", title);
    form.set("format", format);
    form.set("launchUrl", launchUrl);
    if (file) form.set("package", file);
    setStatus("Adding content…");
    const response = await fetch("/api/content", { method: "POST", body: form });
    const data = await response.json();
    if (!response.ok) return setStatus(data.error ?? "Could not add content");
    setItems(data.items ?? []);
    setTitle(""); setLaunchUrl(""); setFile(null);
    setStatus("Content ready for learners");
  }

  async function launch(item: TrainingItem) {
    const response = await fetch("/api/content", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ action: "launch", id: item.id }),
    });
    const data = await response.json();
    if (data.launchUrl) window.open(data.launchUrl, "_blank", "noopener,noreferrer");
    else setStatus("This package does not have a launch target");
    load().catch(() => undefined);
  }

  return <section className="content-hub panel">
    <div className="studio-header"><div><span className="eyebrow">CONNECTED CONTENT</span><h3>Standards-based learning library</h3><p>SCORM packages are hosted securely; AICC courses launch from their external provider.</p></div><div><span className="secure-pill">● SCORM 1.2 · 2004 · AICC</span><small>{status}</small></div></div>
    {role !== "learner" && <div className="content-import">
      <label className="form-field">Content title<input value={title} onChange={(event) => setTitle(event.target.value)} placeholder="e.g. Health & Safety Essentials" /></label>
      <label className="form-field">Format<select value={format} onChange={(event) => setFormat(event.target.value as TrainingItem["format"])}><option value="scorm12">SCORM 1.2</option><option value="scorm2004">SCORM 2004</option><option value="aicc">AICC link</option></select></label>
      {format === "aicc" ? <label className="form-field">Secure AICC launch URL<input type="url" value={launchUrl} onChange={(event) => setLaunchUrl(event.target.value)} placeholder="https://provider.example/course/launch" /></label> : <label className="form-field">SCORM ZIP package<input className="file-input" type="file" accept=".zip,application/zip" onChange={(event) => setFile(event.target.files?.[0] ?? null)} /></label>}
      <button className="primary" onClick={addContent}>Add to library →</button>
    </div>}
    <div className="connected-list">
      {items.length === 0 ? <div className="empty-content"><span>↗</span><strong>No connected courses yet</strong><p>{role === "learner" ? "Your organisation’s SCORM and AICC learning will appear here." : "Upload a SCORM package or add an AICC launch link above."}</p></div> : items.map((item) => <div className="connected-row" key={item.id}><span className={`format-badge ${item.format}`}>{item.format === "scorm12" ? "S12" : item.format === "scorm2004" ? "S04" : "AICC"}</span><div><strong>{item.title}</strong><small>{item.format === "aicc" ? "External course link" : item.packageName} · {item.launches} launches{item.completed ? " · completed" : ""}{item.bestScore !== null && item.bestScore !== undefined ? ` · best ${item.bestScore}%` : ""}</small></div><b>{item.status}</b><button className="outline-button" onClick={() => launch(item)}>Launch course →</button></div>)}
    </div>
    {role !== "learner" && <div className="survey-summary"><div><small>FEEDBACK RESPONSES</small><strong>{survey?.responses ?? 0}</strong></div><div><small>COURSE RATING</small><strong>{survey?.averageRating ?? "—"}<em>/5</em></strong></div><div><small>CONFIDENCE AFTER LEARNING</small><strong>{survey?.averageConfidence ?? "—"}<em>/5</em></strong></div></div>}
  </section>;
}

function FeedbackSurvey() {
  const [rating, setRating] = useState(0);
  const [confidence, setConfidence] = useState(0);
  const [comment, setComment] = useState("");
  const [submitted, setSubmitted] = useState(false);
  async function submit() {
    if (!rating || !confidence) return;
    const response = await fetch("/api/content", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ action: "survey", rating, confidence, comment }),
    });
    if (response.ok) setSubmitted(true);
  }
  return <div className="panel feedback-card">
    <span className="eyebrow">QUICK FEEDBACK</span>
    <h3>{submitted ? "Thank you — feedback saved" : "Help improve this learning"}</h3>
    {submitted ? <p>Your organisation can now see the anonymous course-level feedback trend.</p> : <>
      <div className="survey-question"><strong>How useful was this module?</strong><div>{[1,2,3,4,5].map((value) => <button className={rating === value ? "selected" : ""} key={value} onClick={() => setRating(value)}>{value}</button>)}</div></div>
      <div className="survey-question"><strong>How confident are you applying it?</strong><div>{[1,2,3,4,5].map((value) => <button className={confidence === value ? "selected" : ""} key={value} onClick={() => setConfidence(value)}>{value}</button>)}</div></div>
      <label className="form-field">Anything we should improve? <span>(optional)</span><textarea value={comment} onChange={(event) => setComment(event.target.value)} placeholder="A short comment…" /></label>
      <button className="primary" onClick={submit}>Send feedback →</button>
    </>}
  </div>;
}

function AssessmentCard() {
  const [selected, setSelected] = useState("");
  const [result, setResult] = useState<{ score: number; feedback: string } | null>(null);
  const options = ["Remove a core outcome", "Set aside a contingency reserve", "Ignore the increase until delivery"];
  async function submit() {
    if (!selected) return;
    const response = await fetch("/api/programmes", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ action: "assess", answer: selected }),
    });
    setResult(await response.json());
  }
  return <div className="panel assessment-card">
    <span className="eyebrow">QUICK ASSESSMENT</span>
    <h3>Apply what you learned</h3>
    <p>Your venue cost rises by 10%. What should you do first to protect the project outcome?</p>
    <div className="answer-list">{options.map((option) => <button className={selected === option ? "selected" : ""} key={option} onClick={() => setSelected(option)}>{selected === option ? "●" : "○"} {option}</button>)}</div>
    {!result ? <button className="primary" onClick={submit}>Check my decision →</button> : <div className={result.score === 100 ? "assessment-result good" : "assessment-result"}><strong>{result.score}%</strong><p>{result.feedback}</p></div>}
  </div>;
}

type Submission = {
  id: number;
  projectTitle: string;
  reflection: string;
  fileName: string | null;
  status: string;
  score: number | null;
  rubricFeedback: string | null;
  cvStatement: string | null;
};

function EvidenceSubmission() {
  const [title, setTitle] = useState("Community pop-up event");
  const [reflection, setReflection] = useState("");
  const [file, setFile] = useState<File | null>(null);
  const [status, setStatus] = useState("");
  const [submission, setSubmission] = useState<Submission | null>(null);

  async function submitEvidence() {
    setStatus("Uploading evidence…");
    const form = new FormData();
    form.set("projectTitle", title);
    form.set("reflection", reflection);
    if (file) form.set("file", file);
    const response = await fetch("/api/evidence", { method: "POST", body: form });
    const data = await response.json();
    if (!response.ok) return setStatus(data.error ?? "Could not submit evidence");
    const latest = data.submissions?.[0];
    setSubmission(latest);
    setStatus("Evidence submitted");
  }

  async function assessEvidence() {
    if (!submission) return;
    setStatus("Assessing against the rubric…");
    const response = await fetch("/api/evidence", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ action: "assess", id: submission.id }),
    });
    const data = await response.json();
    setSubmission(data.submissions?.[0] ?? null);
    setStatus("Assessment complete");
  }

  return <div className="panel submission-card">
    <div className="submission-head"><div><span className="eyebrow">PROJECT EVIDENCE</span><h3>Submit what you built</h3></div><span className="secure-pill">● Secure upload</span></div>
    {!submission ? <>
      <div className="submission-grid">
        <label className="form-field">Project title<input value={title} onChange={(event) => setTitle(event.target.value)} /></label>
        <label className="form-field">Evidence file<input className="file-input" type="file" accept=".pdf,.png,.jpg,.jpeg,.txt" onChange={(event) => setFile(event.target.files?.[0] ?? null)} /></label>
      </div>
      <label className="form-field">What did you do, and what was the outcome?<textarea value={reflection} onChange={(event) => setReflection(event.target.value)} placeholder="Describe your role, the decisions you made and the result…" /></label>
      <div className="submission-actions"><button className="primary" onClick={submitEvidence}>Submit evidence →</button><small>{status || "PDF, PNG, JPG or text · Maximum 10 MB"}</small></div>
    </> : <>
      <div className="submitted-proof"><span>✓</span><div><small>SUBMITTED FOR ASSESSMENT</small><strong>{submission.projectTitle}</strong><p>{submission.fileName ? `Attached: ${submission.fileName}` : "Reflection evidence submitted"}</p></div></div>
      {submission.status !== "verified" ? <button className="primary" onClick={assessEvidence}>Assess against rubric →</button> : <RubricResult submission={submission} />}
      <small className="save-note">{status}</small>
    </>}
  </div>;
}

function EvidencePortfolio() {
  const [submissions, setSubmissions] = useState<Submission[]>([]);
  useEffect(() => {
    fetch("/api/evidence").then((response) => response.json()).then((data) => setSubmissions(data.submissions ?? [])).catch(() => undefined);
  }, []);
  const verified = submissions.find((item) => item.status === "verified");
  return <div className="panel portfolio-evidence">
    <span className="eyebrow">CV-READY EXPERIENCE</span>
    <h3>{verified ? "Your verified experience statement" : "Complete an assessed project to unlock this"}</h3>
    {verified ? <>
      <blockquote>{verified.cvStatement}</blockquote>
      <div className="portfolio-meta"><span>✓ Verified project</span><span>{verified.score}% rubric score</span><span>3 demonstrated skills</span></div>
      <button className="outline-button" onClick={() => navigator.clipboard?.writeText(verified.cvStatement ?? "")}>Copy for my CV</button>
    </> : <p>Submit evidence in Build, then assess it against the project rubric. Your verified outcome will appear here automatically.</p>}
  </div>;
}

function RubricResult({ submission }: { submission: Submission }) {
  return <div className="rubric-result">
    <div className="score-ring"><strong>{submission.score}%</strong><small>verified</small></div>
    <div><span className="eyebrow">RUBRIC RESULT</span><h3>Project evidence verified</h3><p>{submission.rubricFeedback}</p><div className="rubric-bars"><span><i style={{ width: "88%" }} />Planning</span><span><i style={{ width: "82%" }} />Application</span><span><i style={{ width: "76%" }} />Outcomes</span></div></div>
  </div>;
}
