function StepProgress({ steps, currentStep, statusFor, onJump }) {
  return (
    <div className="mb-8">
      <div className="flex items-start gap-0">
        {steps.map((s, i) => {
          const status = statusFor(i);
          const isCurrent = i === currentStep;
          const circleClasses =
            status === "complete" ? "bg-emerald-500 border-emerald-500 text-white" :
            isCurrent             ? "bg-navy-600   border-navy-600   text-white" :
            status === "in_progress" ? "bg-amber-50 border-amber-400 text-amber-700" :
            "bg-white border-line-strong text-ink-400";
          const connectorClasses =
            i < currentStep || status === "complete"
              ? "bg-emerald-500"
              : "bg-line";
          return (
            <React.Fragment key={s.key}>
              <button
                type="button"
                onClick={() => onJump(i)}
                className="flex flex-col items-center shrink-0"
                title={`Step ${i + 1}: ${s.label}`}
              >
                <div className={`h-8 w-8 rounded-full border-2 flex items-center justify-center text-xs font-bold ${circleClasses}`}>
                  {status === "complete" ? "✓" : i + 1}
                </div>
                <span className={`mt-2 text-[11px] leading-tight text-center max-w-[100px] ${isCurrent ? "text-navy-600 font-semibold" : "text-ink-600"}`}>
                  {s.label}
                </span>
                {s.optional && <span className="text-[10px] text-ink-400">optional</span>}
              </button>
              {i < steps.length - 1 && (
                <div className="flex-1 h-0.5 mt-4 mx-1">
                  <div className={`h-full ${connectorClasses}`} />
                </div>
              )}
            </React.Fragment>
          );
        })}
      </div>
    </div>
  );
}
function NewProject({ onCreate, onCancel }) {
  const [form, setForm] = useState({
    name: "",
    description: "",
    permittedPurpose: "",
    technologicalInNature: "",
    technicalUncertainty: "",
    processOfExperimentation: ""
  });
  const [step, setStep] = useState(0);
  const [preview, setPreview] = useState(null);
  const STEPS = [
    { key: "basics",         label: "Project basics" },
    { key: "permittedPurpose",        label: "Permitted Purpose" },
    { key: "technologicalInNature",   label: "Technological" },
    { key: "technicalUncertainty",    label: "Uncertainty" },
    { key: "processOfExperimentation",label: "Experimentation" },
    { key: "review",         label: "Review & qualify" },
  ];
  const PRONG_KEYS = ["permittedPurpose","technologicalInNature","technicalUncertainty","processOfExperimentation"];
  function statusFor(i) {
    const s = STEPS[i];
    if (i === step) return "current";
    if (s.key === "basics") {
      const ok = form.name.trim() && form.description.trim();
      return ok ? "complete" : "empty";
    }
    if (s.key === "review") return preview ? "complete" : "empty";
    const v = form[s.key];
    if (!v || !v.trim()) return "empty";
    const sig = signalForProng(s.key, v);
    return sig.score >= 4 ? "complete" : "in_progress";
  }
  const update = (k) => (e) => setForm({ ...form, [k]: e.target.value });
  function runPreview() { setPreview(qualifyProject(form)); }
  function submit() {
    const verdict = qualifyProject(form);
    onCreate({ ...form, verdict });
  }
  function next() { if (step < STEPS.length - 1) setStep(step + 1); }
  function back() { if (step > 0) setStep(step - 1); }
  const current = STEPS[step];
  const PRONG_PLAIN_Q = {
    permittedPurpose:        "What were you trying to do?",
    technologicalInNature:   "What kind of engineering or science does this rely on?",
    technicalUncertainty:    "What was unknown when you started?",
    processOfExperimentation:"What did you try, and what did you measure?",
  };
  const PRONG_HINTS = {
    permittedPurpose:        "Name the new or improved business component you&rsquo;re creating, and the specific function, performance, reliability, or quality improvement it targets.",
    technologicalInNature:   "List the hard-science / engineering / computer-science principles this work relies on, and the specific tech (frameworks, libraries, methods).",
    technicalUncertainty:    "Be specific about what was unknown at the start (capability, methodology, or design) that couldn&rsquo;t be resolved with publicly available information.",
    processOfExperimentation:"Describe the alternatives you evaluated and how (modeling, simulation, trial & error, hypothesis testing), with the metrics that informed each iteration.",
  };
  const PRONG_FULL_LABEL = {
    permittedPurpose: "Permitted Purpose",
    technologicalInNature: "Technological in Nature",
    technicalUncertainty: "Technical Uncertainty",
    processOfExperimentation: "Process of Experimentation",
  };
  return (
    <div className="mx-auto max-w-3xl">
      <div className="mb-6">
        <h1 className="text-2xl sm:text-3xl font-semibold text-ink-900 tracking-tight">Start a new project</h1>
        <p className="mt-2 text-sm text-ink-600">
          We&rsquo;ll walk through this one step at a time. You can jump between steps with the progress bar.
        </p>
      </div>
      <StepProgress steps={STEPS} currentStep={step} statusFor={statusFor} onJump={setStep} />
      <div className="card p-6">
        {current.key === "basics" && (
          <div className="space-y-5">
            <div>
              <h2 className="text-xl font-semibold text-ink-900 tracking-tight">Project basics</h2>
              <p className="mt-1 text-sm text-ink-600">Name the project and describe it in plain English. The AI uses these to tailor every other step.</p>
            </div>
            <label className="block">
              <span className="text-sm font-medium text-ink-900">Project name<span className="text-rose-600">*</span></span>
              <input
                value={form.name}
                onChange={update("name")}
                placeholder="e.g. Multi-Tenant Platform Architecture"
                className="input mt-1.5"
              />
            </label>
            <label className="block">
              <span className="text-sm font-medium text-ink-900">Description (1-2 sentences)<span className="text-rose-600">*</span></span>
              <p className="mt-1 text-xs text-ink-600">A short, plain-English description anyone on the team would understand.</p>
              <textarea
                rows={3}
                value={form.description}
                onChange={update("description")}
                className="input mt-1.5"
                placeholder="What is this project about? What component or capability is being built or improved?"
              />
            </label>
          </div>
        )}
        {PRONG_KEYS.includes(current.key) && (
          <div className="space-y-4">
            <div>
              <p className="text-xs uppercase tracking-[0.14em] font-semibold text-ink-400">Step {step + 1} of {STEPS.length} · §41 four-part test</p>
              <h2 className="mt-1 text-xl sm:text-2xl font-semibold text-ink-900 tracking-tight">{PRONG_FULL_LABEL[current.key]}</h2>
              <h3 className="mt-2 text-base italic text-ink-600">{PRONG_PLAIN_Q[current.key]}</h3>
              <p className="mt-2 text-sm text-ink-600" dangerouslySetInnerHTML={{ __html: PRONG_HINTS[current.key] }} />
            </div>
            <EnhancedField
              prong={current.key}
              label=""
              hint=""
              rows={7}
              value={form[current.key]}
              onChange={update(current.key)}
              projectName={form.name}
              description={form.description}
            />
          </div>
        )}
        {current.key === "review" && (
          <div className="space-y-5">
            <div>
              <h2 className="text-xl font-semibold text-ink-900 tracking-tight">Review &amp; qualify</h2>
              <p className="mt-1 text-sm text-ink-600">
                Read through your answers. Run the qualification engine to see your verdict before you submit.
              </p>
            </div>
            <div className="space-y-3 text-sm">
              <ReviewRow label="Project name"  value={form.name} onEdit={() => setStep(0)} />
              <ReviewRow label="Description"   value={form.description} onEdit={() => setStep(0)} />
              <ReviewRow label="Permitted Purpose"          value={form.permittedPurpose}        onEdit={() => setStep(2)} />
              <ReviewRow label="Technological in Nature"    value={form.technologicalInNature}   onEdit={() => setStep(3)} />
              <ReviewRow label="Technical Uncertainty"      value={form.technicalUncertainty}    onEdit={() => setStep(4)} />
              <ReviewRow label="Process of Experimentation" value={form.processOfExperimentation} onEdit={() => setStep(5)} />
            </div>
            {preview && <QualificationPanel verdict={preview} />}
            <div className="flex items-center justify-between gap-3 pt-2">
              <button type="button" className="btn-secondary" onClick={runPreview}>
                {preview ? "Re-run qualification preview" : "Preview qualification"}
              </button>
              <button type="button" className="btn-primary" onClick={submit}>
                Save &amp; create project
              </button>
            </div>
          </div>
        )}
        <div className="mt-6 pt-5 border-t border-line flex items-center justify-between">
          <button type="button" onClick={step === 0 ? onCancel : back} className="btn-ghost">
            {step === 0 ? "Cancel" : "← Back"}
          </button>
          <div className="text-xs text-ink-400">Step {step + 1} of {STEPS.length}</div>
          {step < STEPS.length - 1 ? (
            <button type="button" onClick={next} className="btn-primary">Next →</button>
          ) : (
            <button type="button" onClick={submit} className="btn-primary">Save &amp; create project</button>
          )}
        </div>
      </div>
    </div>
  );
}
function ReviewRow({ label, value, onEdit }) {
  return (
    <div className="rounded-md border border-line bg-white p-3">
      <div className="flex items-start justify-between gap-3">
        <span className="text-xs font-semibold uppercase tracking-wider text-ink-400">{label}</span>
        <button type="button" onClick={onEdit} className="text-xs text-navy-600 hover:underline shrink-0">Edit</button>
      </div>
      {value && value.trim() ? (
        <p className="mt-1 whitespace-pre-wrap text-sm text-ink-900">{value}</p>
      ) : (
        <p className="mt-1 text-sm italic text-rose-600">Empty — click Edit to add content.</p>
      )}
    </div>
  );
}
function QualificationPanel({ verdict }) {
  if (!verdict) return null;
  return (
    <section className="card p-6">
      <div className="flex items-center gap-3">
        <h2 className="text-lg font-semibold text-ink-900 tracking-tight">Qualification</h2>
        <VerdictBadge verdict={verdict.status} />
      </div>
      {verdict.hardDisqualifiers.length > 0 && (
        <div className="mt-4 rounded-md border border-rose-200 bg-rose-50 p-4">
          <p className="text-sm font-semibold text-rose-800">Hard disqualification rules triggered:</p>
          <ul className="mt-2 list-disc pl-5 text-sm text-rose-800">
            {verdict.hardDisqualifiers.map((c) => <li key={c}>{describeHardRule(c)}</li>)}
          </ul>
        </div>
      )}
      <div className="mt-4 grid grid-cols-2 sm:grid-cols-4 gap-4">
        {Object.entries(verdict.prongScores).map(([prong, score]) => (
          <div key={prong} className="rounded-md border border-line bg-cream-50 p-3">
            <div className="text-xs uppercase tracking-wider text-ink-400">{PRONG_LABEL[prong]}</div>
            <div className="mt-1 flex items-baseline gap-1.5">
              <span className="text-2xl font-bold text-navy-600">{score}</span>
              <span className="text-sm text-ink-400">/ 5</span>
            </div>
            <p className="mt-2 text-xs leading-relaxed text-ink-600">{verdict.reasoning[prong]}</p>
          </div>
        ))}
      </div>
      {verdict.suggestedFollowUp && (
        <div className="mt-4 rounded-md border border-amber-200 bg-amber-50 p-4">
          <p className="text-sm font-semibold text-amber-800">Suggested follow-up</p>
          <p className="mt-1 text-sm text-amber-900">{verdict.suggestedFollowUp}</p>
        </div>
      )}
      <div className="mt-4 text-xs text-ink-400">
        Confidence: <span className="font-medium">{verdict.confidence}</span> · Model:{" "}
        <span className="font-mono">{verdict.model}</span> · Prompt:{" "}
        <span className="font-mono">{verdict.promptVersion}</span>
      </div>
    </section>
  );
}
function ProjectDetail({ project, onAddNote, onAddExpense }) {
  const [note, setNote] = useState("");
  const [exp, setExp] = useState({ category: "wages", payeeName: "", period: "2025-FY", amount: "", qualifiedPercent: "1.0" });
  const verdict = project.verdictResult || (project.verdict ? { status: project.verdict, prongScores: project.prongScoresStored || {permitted_purpose:5,technological:5,uncertainty:5,experimentation:5}, reasoning: project.reasoningStored || {permitted_purpose:"",technological:"",uncertainty:"",experimentation:""}, hardDisqualifiers: project.hardDisqualifiers || [], suggestedFollowUp: null, confidence: project.confidence || "medium", model: "stub-in-browser", promptVersion: "v1.0.0" } : null);
  const total = totalQREForProject(project);
  function submitNote(e) {
    e.preventDefault();
    if (!note.trim()) return;
    onAddNote(project.id, note.trim());
    setNote("");
  }
  function submitExpense(e) {
    e.preventDefault();
    const amt = parseFloat(exp.amount);
    const qp = parseFloat(exp.qualifiedPercent);
    if (!exp.payeeName.trim() || isNaN(amt)) return;
    onAddExpense(project.id, { ...exp, amount: amt, qualifiedPercent: qp });
    setExp({ ...exp, payeeName: "", amount: "" });
  }
  return (
    <div>
      <div className="mb-6">
        <div className="flex flex-wrap items-center gap-3">
          <h1 className="text-2xl sm:text-3xl font-semibold text-ink-900 tracking-tight">{project.name}</h1>
          <VerdictBadge verdict={project.verdict} />
        </div>
        <p className="mt-2 text-sm text-ink-600">{project.description}</p>
      </div>
      <div className="mb-8">
        <QualificationPanel verdict={verdict} />
      </div>
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <section className="lg:col-span-1">
          <div className="card p-5">
            <h2 className="text-base font-semibold text-ink-900 tracking-tight">Notes</h2>
            <p className="mt-1 text-xs text-ink-600">What did you work on this week? What did you try? What didn&rsquo;t work?</p>
            <form onSubmit={submitNote} className="mt-3 space-y-2">
              <textarea rows={4} value={note} onChange={(e) => setNote(e.target.value)} className="input" placeholder="Type a quick update..." />
              <button className="btn-primary w-full" type="submit">Save note · update narrative</button>
            </form>
          </div>
          <ul className="mt-4 space-y-3">
            {project.notes.length === 0 && <li className="text-xs text-ink-400">No notes yet.</li>}
            {project.notes.map((n) => (
              <li key={n.id} className="rounded-md border border-line bg-white p-3 text-sm">
                <p className="whitespace-pre-wrap text-ink-900">{n.body}</p>
                <p className="mt-2 text-xs text-ink-400">{new Date(n.createdAt).toLocaleString()}</p>
              </li>
            ))}
          </ul>
        </section>
        <section className="lg:col-span-2 space-y-6">
          <div className="card p-5">
            <h2 className="text-base font-semibold text-ink-900 tracking-tight">§41 Narrative</h2>
            <p className="mt-1 text-xs text-ink-600">AI converts your notes into draft updates for each section. Edit freely; changes are versioned.</p>
            <div className="mt-4 space-y-4">
              {SECTION_ORDER.map((s) => {
                const draft = project.narratives?.[s] || "";
                return (
                  <div key={s} className="rounded-md border border-line p-3">
                    <h3 className="text-sm font-semibold text-ink-900">{SECTION_LABELS[s]}</h3>
                    {draft
                      ? <p className="mt-2 whitespace-pre-wrap text-sm text-ink-900">{draft}</p>
                      : <p className="mt-2 text-xs italic text-ink-400">No draft yet — add a note and the AI will propose one.</p>
                    }
                  </div>
                );
              })}
            </div>
          </div>
          <div className="card p-5">
            <h2 className="text-base font-semibold text-ink-900 tracking-tight">Expenses</h2>
            <p className="mt-1 text-xs text-ink-600">
              Captured QRE so far on this project (after 65% contractor adjustment): <span className="font-semibold text-ink-900">{fmtMoney(total)}</span>
            </p>
            <form onSubmit={submitExpense} className="mt-4 grid grid-cols-2 md:grid-cols-5 gap-3 rounded-md border border-line bg-cream-50 p-3">
              <select className="input" value={exp.category} onChange={(e) => setExp({ ...exp, category: e.target.value })}>
                <option value="wages">Wages (W-2)</option>
                <option value="officer_comp">Officer / Owner</option>
                <option value="contractor">Contractor</option>
                <option value="supply">Supply</option>
                <option value="cloud">Cloud Hosting</option>
              </select>
              <input className="input" required placeholder="Name / vendor" value={exp.payeeName} onChange={(e) => setExp({ ...exp, payeeName: e.target.value })} />
              <input className="input" required placeholder="2025-FY" value={exp.period} onChange={(e) => setExp({ ...exp, period: e.target.value })} />
              <input className="input" required type="number" step="0.01" placeholder="Amount" value={exp.amount} onChange={(e) => setExp({ ...exp, amount: e.target.value })} />
              <input className="input" type="number" step="0.01" min="0" max="1" placeholder="Qualified %" value={exp.qualifiedPercent} onChange={(e) => setExp({ ...exp, qualifiedPercent: e.target.value })} />
              <button className="btn-primary md:col-span-5" type="submit">Add expense</button>
            </form>
            <ul className="mt-4 divide-y divide-line text-sm">
              {project.expenses.length === 0 && <li className="py-3 text-xs text-ink-400">No expenses captured yet.</li>}
              {project.expenses.map((e) => (
                <li key={e.id} className="flex items-center justify-between py-2">
                  <div>
                    <span className="font-medium">{e.payeeName}</span>
                    <span className="ml-2 text-xs text-ink-400">{e.category} · {e.period}</span>
                  </div>
                  <div className="text-sm">{fmtMoney(e.amount)} · {(e.qualifiedPercent * 100).toFixed(0)}%</div>
                </li>
              ))}
            </ul>
          </div>
        </section>
      </div>
    </div>
  );
}
function AdminRollup({ projects, onOpenEngagement }) {
  const qre = sumQRE(projects);
  const counts = { qualified: 0, borderline: 0, disqualified: 0, pending: 0 };
  for (const p of projects) counts[p.verdict] = (counts[p.verdict] || 0) + 1;
  const credit = qre * 0.06;
  return (
    <div>
      <div className="mb-6">
        <h1 className="text-2xl sm:text-3xl font-semibold text-ink-900 tracking-tight">Engagements</h1>
        <p className="mt-2 text-sm text-ink-600">All active client engagements. Estimated credit assumes the 6% startup flat rate; actual study calc is finalized at year-end.</p>
      </div>
      <div className="card overflow-hidden">
        <table className="w-full text-sm">
          <thead className="border-b border-line bg-cream-50">
            <tr className="text-left text-xs uppercase tracking-wider text-ink-600">
              <th className="px-4 py-3 font-semibold">Client</th>
              <th className="px-4 py-3 font-semibold">Tax year</th>
              <th className="px-4 py-3 text-right font-semibold">Projects</th>
              <th className="px-4 py-3 text-right font-semibold">Qual / Border / Disq</th>
              <th className="px-4 py-3 text-right font-semibold">Captured QRE</th>
              <th className="px-4 py-3 text-right font-semibold">Est. credit (6%)</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-line">
            <tr className="hover:bg-cream-50 cursor-pointer" onClick={() => onOpenEngagement(ENGAGEMENT.id)}>
              <td className="px-4 py-3">
                <button className="font-medium text-navy-600 hover:underline">{ENGAGEMENT.clientName}</button>
              </td>
              <td className="px-4 py-3">{ENGAGEMENT.taxYear}</td>
              <td className="px-4 py-3 text-right">{projects.length}</td>
              <td className="px-4 py-3 text-right">
                <span className="text-emerald-700">{counts.qualified || 0}</span> / <span className="text-amber-700">{counts.borderline || 0}</span> / <span className="text-rose-700">{counts.disqualified || 0}</span>
              </td>
              <td className="px-4 py-3 text-right">{fmtMoney(qre)}</td>
              <td className="px-4 py-3 text-right font-semibold">{fmtMoney(credit)}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  );
}
function EngagementDetail({ projects, onOpenProject, onBack }) {
  function exportPackage() {
    const lines = [`Windstone R&D Export — ${ENGAGEMENT.clientName} — Tax Year ${ENGAGEMENT.taxYear}`, "Exported " + new Date().toLocaleString(), ""];
    let total = 0;
    for (const p of projects) {
      const q = totalQREForProject(p);
      total += q;
      lines.push(`${p.name}\t${p.verdict}\t${fmtMoney(q)}`);
    }
    lines.push("", `TOTAL QRE\t\t${fmtMoney(total)}`);
    lines.push(`ESTIMATED CREDIT (6%)\t\t${fmtMoney(total * 0.06)}`);
    const blob = new Blob([lines.join("\n")], { type: "text/tab-separated-values" });
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = `Windstone_QRE_${ENGAGEMENT.clientName.replace(/[^a-z0-9]/gi,"_")}_${ENGAGEMENT.taxYear}.tsv`;
    document.body.appendChild(a); a.click(); a.remove();
  }
  return (
    <div>
      <button onClick={onBack} className="btn-ghost mb-2">← All engagements</button>
      <div className="mb-6 flex items-end justify-between">
        <div>
          <p className="text-xs uppercase tracking-[0.14em] font-semibold text-ink-400">Engagement · Tax Year {ENGAGEMENT.taxYear}</p>
          <h1 className="text-2xl sm:text-3xl font-semibold text-ink-900 tracking-tight">{ENGAGEMENT.clientName}</h1>
          <p className="mt-1 text-sm text-ink-600">EIN: {ENGAGEMENT.ein}</p>
        </div>
        <button className="btn-primary" onClick={exportPackage}>Export year-end package</button>
      </div>
      <div className="card overflow-hidden">
        <table className="w-full text-sm">
          <thead className="border-b border-line bg-cream-50">
            <tr className="text-left text-xs uppercase tracking-wider text-ink-600">
              <th className="px-4 py-3">Project</th>
              <th className="px-4 py-3">Verdict</th>
              <th className="px-4 py-3 text-right">QRE</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-line">
            {projects.map((p) => (
              <tr key={p.id} className="hover:bg-cream-50 cursor-pointer" onClick={() => onOpenProject(p.id)}>
                <td className="px-4 py-3">
                  <button className="font-medium text-navy-600 hover:underline text-left">{p.name}</button>
                  <p className="mt-0.5 line-clamp-1 text-xs text-ink-600">{p.description}</p>
                </td>
                <td className="px-4 py-3"><VerdictBadge verdict={p.verdict} /></td>
                <td className="px-4 py-3 text-right">{fmtMoney(totalQREForProject(p))}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
function App() {
  const [user, setUser] = useState(null);
  const [page, setPage] = useState("landing");
  const [projectId, setProjectId] = useState(null);
  const [projects, setProjects] = useState(SEED_PROJECTS);
  const visibleProjects = useMemo(() => {
    if (!user) return [];
    return projects;
  }, [user, projects]);
  const activeProject = projects.find((p) => p.id === projectId);
  function signIn(u) {
    setUser(u);
    setPage(u.role === "windstone_admin" ? "admin-rollup" : "contributor-list");
  }
  function signOut() { setUser(null); setPage("landing"); }
  function nav(p) { setPage(p); }
  function openProject(id) { setProjectId(id); setPage("project-detail"); }
  function createProject(form) {
    const id = "p-" + Math.random().toString(36).slice(2, 8);
    const np = {
      id,
      name: form.name,
      description: form.description,
      permittedPurpose: form.permittedPurpose,
      technologicalInNature: form.technologicalInNature,
      technicalUncertainty: form.technicalUncertainty,
      processOfExperimentation: form.processOfExperimentation,
      verdict: form.verdict.status,
      verdictResult: form.verdict,
      expenses: [],
      narratives: {
        permitted_purpose: form.permittedPurpose,
        technological_in_nature: form.technologicalInNature,
        technical_uncertainty: form.technicalUncertainty,
        process_of_experimentation: form.processOfExperimentation
      },
      notes: []
    };
    setProjects([np, ...projects]);
    setProjectId(id);
    setPage("project-detail");
  }
  function addNote(pid, body) {
    setProjects(projects.map((p) => {
      if (p.id !== pid) return p;
      const note = { id: "n" + Math.random().toString(36).slice(2,6), body, createdAt: new Date().toISOString() };
      const result = generateNarrativeUpdates({
        projectName: p.name,
        projectDescription: p.description,
        priorDrafts: p.narratives || {},
        newNote: body
      });
      const newNarratives = { ...(p.narratives || {}) };
      for (const d of result.deltas) newNarratives[d.section] = d.proposedDraft;
      return { ...p, notes: [note, ...p.notes], narratives: newNarratives };
    }));
  }
  function addExpense(pid, e) {
    setProjects(projects.map((p) => p.id === pid
      ? { ...p, expenses: [...p.expenses, { id: "e" + Math.random().toString(36).slice(2,6), ...e }] }
      : p));
  }
  if (!user) return <Landing onSignIn={signIn} />;
  return (
    <div className="min-h-screen">
      <Header user={user} onSignOut={signOut} onNav={nav} currentPage={page} />
      <main className="mx-auto max-w-6xl px-6 py-8">
        {page === "contributor-list" && (
          <ContributorList projects={visibleProjects} user={user} onOpenProject={openProject} onNew={() => setPage("new-project")} />
        )}
        {page === "new-project" && (
          <NewProject onCreate={createProject} onCancel={() => setPage("contributor-list")} />
        )}
        {page === "project-detail" && activeProject && (
          <ProjectDetail project={activeProject} onAddNote={addNote} onAddExpense={addExpense} />
        )}
        {page === "admin-rollup" && (
          <AdminRollup projects={visibleProjects} onOpenEngagement={(id) => { setPage("engagement-detail"); }} />
        )}
        {page === "engagement-detail" && (
          <EngagementDetail projects={visibleProjects} onOpenProject={openProject} onBack={() => setPage("admin-rollup")} />
        )}
      </main>
    </div>
  );
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
