
const HARD_RULES = [
  { code: "foreign_research", description: "Research conducted outside the United States, Puerto Rico, or other U.S. possessions (IRC §41(d)(4)(F)).", trigger: (t) => /(\bbased in (india|canada|europe|uk|brazil|china|mexico)|offshore team|developed (in|by) (india|canada|europe))/i.test(t) },
  { code: "post_commercial_production", description: "Research after commercial production has begun (IRC §41(d)(4)(A); Treas. Reg. §1.41-4(c)(2)).", trigger: (t) => /(after launch|post-?launch|production hotfix|after general availability|post-?ga)/i.test(t) },
  { code: "customer_specific_adaptation", description: "Customer-specific adaptation of an existing business component (IRC §41(d)(4)(B)).", trigger: (t) => /(one-off customization for|custom build for a single customer|per-customer adaptation|bespoke implementation for)/i.test(t) },
  { code: "duplication_existing_product", description: "Duplication of an existing business component from physical examination (IRC §41(d)(4)(C)).", trigger: (t) => /(reverse engineer|reverse-engineer|clone of competitor|reproduce the competitor)/i.test(t) },
  { code: "surveys_market_research", description: "Surveys, studies, market research, or routine data collection (IRC §41(d)(4)(D)).", trigger: (t) => /(market research|customer survey|voice of customer|consumer research panel)/i.test(t) },
  { code: "routine_qc", description: "Routine data collection or quality-control testing (IRC §41(d)(4)(E)).", trigger: (t) => /(routine qa|routine quality control|regression testing of unchanged)/i.test(t) },
  { code: "social_science_arts_humanities", description: "Research in the social sciences, arts, or humanities (IRC §41(d)(3)(B)).", trigger: (t) => /(purely behavioral study|literature review|art-historical analysis|humanities research)/i.test(t) },
  { code: "funded_research", description: "Research funded by a grant or contract that retains risk and rights with the funder (IRC §41(d)(4)(H)).", trigger: (t) => /(fully funded by grant|sbir grant covers all|customer bears the financial risk)/i.test(t) },
];
function isAestheticOnly(input) {
  const txt = (input.name + " " + input.description).toLowerCase();
  const looks = ["marketing site redesign","logo refresh","brand refresh","visual refresh","rebranding","color palette change"].some(p => txt.includes(p));
  const hasTechExp = (input.technicalUncertainty || "").trim().length > 30 && (input.processOfExperimentation || "").trim().length > 30;
  return looks && !hasTechExp;
}
function describeHardRule(code) {
  const r = HARD_RULES.find(r => r.code === code);
  if (r) return r.description;
  if (code === "aesthetic_only") return "Pure aesthetic or style work without underlying technical experimentation (Treas. Reg. §1.41-4(a)(8)).";
  return code;
}
function runHardRules(input) {
  const txt = [input.name, input.description, input.permittedPurpose, input.technologicalInNature, input.technicalUncertainty, input.processOfExperimentation].filter(Boolean).join("\n");
  const triggered = [];
  for (const r of HARD_RULES) if (r.trigger(txt)) triggered.push(r.code);
  if (isAestheticOnly(input)) triggered.push("aesthetic_only");
  return triggered;
}
function stubScore(input) {
  const len = (s) => (s || "").trim().length;
  const has = (s, words) => !!s && words.some(w => s.toLowerCase().includes(w));
  const technologicalSignals = ["engineering","software","computer science","algorithm","distributed","machine learning"," ml ","ai","physics","chemistry","biology","hardware","cryptograph","compiler","database"];
  const uncertaintySignals = ["uncertain","unclear","did not know","could not","unknown","open question","open problem","feasibility","unproven"];
  const experimentationSignals = ["tested","experiment","iterated","prototyped","simulated","benchmarked","a/b","ab test","trial and error","measured","load test"];
  const purpose = len(input.permittedPurpose) > 60 ? 4 : len(input.permittedPurpose) > 20 ? 3 : 2;
  const tech = has(input.technologicalInNature, technologicalSignals)
    ? (len(input.technologicalInNature) > 80 ? 5 : 4)
    : (len(input.technologicalInNature) > 40 ? 3 : 2);
  const uncert = has(input.technicalUncertainty, uncertaintySignals) && len(input.technicalUncertainty) > 80
    ? 5
    : len(input.technicalUncertainty) > 80 ? 4
    : len(input.technicalUncertainty) > 30 ? 3 : 1;
  const exp = has(input.processOfExperimentation, experimentationSignals) && len(input.processOfExperimentation) > 80
    ? 5
    : len(input.processOfExperimentation) > 80 ? 4
    : len(input.processOfExperimentation) > 30 ? 3 : 1;
  const prongScores = {
    permitted_purpose: purpose,
    technological: tech,
    uncertainty: uncert,
    experimentation: exp
  };
  const reasoning = {
    permitted_purpose: purpose >= 4 ? "Clear improvement to a business component is described." : "Improvement is asserted but not clearly tied to a specific business component.",
    technological:     tech    >= 4 ? "Relies on principles of engineering or computer science." : "Technological grounding is not concretely established.",
    uncertainty:       uncert  >= 4 ? "Specific uncertainty at the outset is identified."        : "Uncertainty is mentioned but not specifically described as present at project start.",
    experimentation:   exp     >= 4 ? "Systematic alternatives evaluation is described."        : "Process of evaluating alternatives is not detailed."
  };
  const entries = Object.entries(prongScores).sort((a,b) => a[1] - b[1]);
  const weakest = entries[0];
  const labels = { permitted_purpose: "Permitted Purpose", technological: "Technological in Nature", uncertainty: "Technical Uncertainty", experimentation: "Process of Experimentation" };
  const suggestedFollowUp = weakest[1] < 4
    ? `Please strengthen "${labels[weakest[0]]}" — describe specifically what was unknown at the start and what alternatives you evaluated.`
    : null;
  return { prongScores, reasoning, suggestedFollowUp };
}
function deriveVerdict(scores, hardDisqualifiers, strict) {
  if (hardDisqualifiers.length > 0) return { status: "disqualified", confidence: "high" };
  const values = Object.values(scores);
  const allSatisfied = values.every(v => v >= 4);
  const anyBelow3 = values.some(v => v < 3);
  const twoOrMoreBelow4 = values.filter(v => v < 4).length >= 2;
  if (allSatisfied) {
    const min = Math.min(...values);
    return { status: "qualified", confidence: min >= 5 ? "high" : "medium" };
  }
  if (anyBelow3 || twoOrMoreBelow4) return { status: "disqualified", confidence: "medium" };
  return { status: strict ? "borderline" : "qualified", confidence: "medium" };
}
function qualifyProject(input, opts = {}) {
  const strict = opts.strict !== false;
  const hardDisqualifiers = runHardRules(input);
  let scoreResult;
  if (hardDisqualifiers.length > 0) {
    scoreResult = {
      prongScores: { permitted_purpose: 1, technological: 1, uncertainty: 1, experimentation: 1 },
      reasoning: {
        permitted_purpose: "Skipped — hard disqualifier triggered.",
        technological: "Skipped — hard disqualifier triggered.",
        uncertainty: "Skipped — hard disqualifier triggered.",
        experimentation: "Skipped — hard disqualifier triggered."
      },
      suggestedFollowUp: "This project hits a hard disqualification rule under IRC §41(d). Review the disqualifier reasoning above before proceeding."
    };
  } else {
    scoreResult = stubScore(input);
  }
  const v = deriveVerdict(scoreResult.prongScores, hardDisqualifiers, strict);
  return {
    status: v.status,
    confidence: v.confidence,
    prongScores: scoreResult.prongScores,
    hardDisqualifiers,
    reasoning: scoreResult.reasoning,
    suggestedFollowUp: scoreResult.suggestedFollowUp,
    promptVersion: "v1.0.0",
    model: "stub-in-browser"
  };
}
const SECTION_LABELS = {
  business_component: "Business Component",
  permitted_purpose: "Permitted Purpose",
  technical_uncertainty: "Technical Uncertainty",
  process_of_experimentation: "Process of Experimentation",
  technological_in_nature: "Technological in Nature",
  result: "Result"
};
const SECTION_ORDER = Object.keys(SECTION_LABELS);
function generateNarrativeUpdates({ projectName, projectDescription, priorDrafts, newNote }) {
  const note = newNote.toLowerCase();
  let target = "permitted_purpose";
  if (/(uncertain|unknown|did not know|unclear|tricky|wasn't sure|figuring out)/.test(note))             target = "technical_uncertainty";
  else if (/(tested|tried|prototype|experiment|iterated|benchmarked|measured|load test|a\/b|spike)/.test(note)) target = "process_of_experimentation";
  else if (/(achieved|delivered|result|shipped|improved by|reduced|increased|works now|stable now)/.test(note))  target = "result";
  else if (/(framework|language|algorithm|architecture|database|stack|kafka|postgres|llm|ml model)/.test(note)) target = "technological_in_nature";
  else if (/(component|system|module|service|tool|product|feature|platform)/.test(note))                   target = "business_component";
  const prior = priorDrafts[target] || "";
  const proposed = prior
    ? prior + "\n\n" + "Update from contributor note: " + newNote
    : "Drafted from contributor note: " + newNote;
  return {
    deltas: [{
      section: target,
      proposedDraft: proposed,
      rationale: `Routed into ${SECTION_LABELS[target]} based on keywords (stub mode).`
    }]
  };
}
const ENGAGEMENT = {
  id: "keep-2025",
  clientName: "Keep Company, Inc.",
  ein: "88-1651256",
  taxYear: 2025,
  priorYearQRE: 52710,
  strictQualification: true
};
const USERS = {
  admin:   { id: "u-colin", name: "Colin Van Balen", email: "colin@windstonefinancial.com", role: "windstone_admin" },
  tenant:  { id: "u-zvi",   name: "Zvi Band",        email: "zvi@keepcompany.example",      role: "tenant_admin",  engagementId: "keep-2025" },
  contrib: { id: "u-meg",   name: "Meg Young",       email: "meg@keepcompany.example",      role: "contributor",   engagementId: "keep-2025" }
};
const SEED_PROJECTS = [
  {
    id: "p-sso", name: "Single Sign-On (SSO) Authentication", description: "Enterprise-grade SSO that lets members, admins, and coaches access the Keep Company platform via their organization's identity provider. Replaces magic-link-only auth and enables tenant-specific identity enforcement.",
    permittedPurpose: "Create an improved authentication component enabling secure federated authentication across multiple identity providers and tenants, resulting in stronger security and a more reliable login experience.",
    technologicalInNature: "Identity and access management, federated authentication protocols (SAML, OIDC, JWT), cryptographic token validation, session management, multi-tenant system design.",
    technicalUncertainty: "Uncertain whether a single integration approach could handle multiple identity providers with consistent behavior. Token lifecycle, tenant isolation, and the direct-vs-broker integration decision were all unresolved at the start.",
    processOfExperimentation: "Tested brokered identity providers against direct integrations; conducted staged rollouts; simulated token expiration and replay; iterated session-handling logic until stable.",
    verdict: "qualified", confidence: "medium",
    expenses: [
      { id:"e1", category:"wages",        payeeName:"Zvi Band",  period:"2025-FY", amount: 5948, qualifiedPercent: 1.0 },
      { id:"e2", category:"wages",        payeeName:"Meg Young", period:"2025-FY", amount:  703, qualifiedPercent: 1.0 },
      { id:"e3", category:"cloud",        payeeName:"AWS / Vercel / GitHub", period:"2025-FY", amount: 887, qualifiedPercent: 1.0 }
    ],
    narratives: {
      business_component: "Single Sign-On (SSO) authentication integrated into the Keep Company platform. Replaces a magic-link-only approach and enables tenant-specific identity enforcement.",
      permitted_purpose: "Create an improved authentication component for federated identity across enterprise tenants.",
      technical_uncertainty: "Uncertainty around identity-provider compatibility, token lifecycle, tenant isolation, and the build-vs-broker decision.",
      process_of_experimentation: "Tested brokered providers vs. direct integration; staged tenant rollouts; simulated token expiration and replay scenarios; iterated session logic.",
      technological_in_nature: "Identity and access management, SAML/OIDC, cryptographic token validation, multi-tenant design.",
      result: "Delivered enterprise-grade SSO with tenant-scoped identity enforcement and improved security posture."
    },
    notes: [
      { id:"n1", body:"Decided to evaluate WorkOS vs. building direct SAML adapters. Built a small spike for each so we can compare reliability and config overhead.", createdAt: "2025-02-12T15:30:00Z" },
      { id:"n2", body:"Simulated token replay against three IdPs. Caught a refresh-flow bug that didn't show in unit tests — fixed and re-ran the simulation.", createdAt: "2025-03-04T19:10:00Z" }
    ]
  },
  {
    id: "p-multi-tenant", name: "Multi-Tenant Platform Architecture", description: "Replace single-tenant architecture with shared infrastructure that preserves strict tenant data isolation, configurable branding, and independent program configurations.",
    permittedPurpose: "Create an improved software architecture that supports enterprise deployment on shared infrastructure while preserving strict tenant data isolation, resulting in lower operational cost and faster customer onboarding.",
    technologicalInNature: "Distributed-systems design, database partitioning, role-based access control, multi-tenant identity management, observability, deployment automation.",
    technicalUncertainty: "Whether shared infrastructure could maintain strict tenant isolation without performance degradation; optimal database partitioning strategy across mixed tenant sizes; how to manage tenant-specific configurations without code branching.",
    processOfExperimentation: "Synthetic multi-tenant load testing; prototyped tenant-scoped configuration layers and compared extensibility; iterated RBAC and permission inheritance models; tested authentication-isolation logic; refined deployment and rollback strategies.",
    verdict: "qualified", confidence: "high",
    expenses: [
      { id:"e4", category:"wages",  payeeName:"Zvi Band",  period:"2025-FY", amount: 23425, qualifiedPercent: 1.0 },
      { id:"e5", category:"wages",  payeeName:"Meg Young", period:"2025-FY", amount:  3770, qualifiedPercent: 1.0 },
      { id:"e6", category:"cloud",  payeeName:"AWS / Vercel / GitHub", period:"2025-FY", amount: 3744, qualifiedPercent: 1.0 }
    ],
    narratives: {
      business_component: "Multi-tenant platform architecture that enables multiple enterprise clients to operate within shared infrastructure with strict data isolation.",
      permitted_purpose: "Support scalable enterprise deployment on shared infrastructure with strict tenant isolation, configurable branding, and independent program configurations.",
      technical_uncertainty: "Could shared infrastructure maintain strict isolation without performance loss? Which database partitioning strategy works across mixed tenant sizes? How to manage tenant-specific configuration without code branching?",
      process_of_experimentation: "Synthetic multi-tenant load testing; prototyped tenant-scoped config layers; iterated RBAC and permission inheritance; tested auth-isolation alongside SSO; refined deployment and rollback strategies.",
      technological_in_nature: "Distributed-systems design, database partitioning, RBAC, multi-tenant identity management, observability, deployment automation.",
      result: "Delivered a multi-tenant architecture supporting scalable enterprise deployment with strict isolation and reduced per-customer infrastructure cost."
    },
    notes: [
      { id:"n3", body:"Load test with 50 synthetic tenants. p99 latency stayed under 240ms which is the threshold we agreed on. Surprised by how well row-level security held up under concurrent writes.", createdAt: "2025-04-15T18:20:00Z" }
    ]
  },
  {
    id: "p-ai-commitment", name: "AI-Generated Commitment Plans", description: "AI-assisted commitment-plan generation that converts user meeting checkouts and qualitative inputs into structured, personalized follow-through plans. Includes a firm-level PII detection and scrubbing layer for outbound data to external AI services.",
    permittedPurpose: "Create an improved software component that produces psychologically safe, behavior-change-oriented commitment plans at scale, resulting in higher participant follow-through and reduced compliance risk.",
    technologicalInNature: "Natural-language processing, prompt engineering with large language models (LLMs), validation and rule-based systems, privacy-preserving data handling, API integration design.",
    technicalUncertainty: "Whether generative AI could consistently produce supportive, non-directive language at scale; which prompt structures could reliably transform multi-goal commitments into actionable plans; how to reliably detect PII without losing semantic context.",
    processOfExperimentation: "Prototyped multiple prompt architectures and output templates; ran batch generation against anonymized scenarios; iterated tone, length, structure; developed validation logic for multi-goal detection; conducted side-by-side output reviews.",
    verdict: "qualified", confidence: "medium",
    expenses: [
      { id:"e7", category:"wages", payeeName:"Zvi Band",  period:"2025-FY", amount: 7692, qualifiedPercent: 1.0 },
      { id:"e8", category:"wages", payeeName:"Meg Young", period:"2025-FY", amount: 4685, qualifiedPercent: 1.0 },
      { id:"e9", category:"cloud", payeeName:"OpenAI / AWS / GitHub", period:"2025-FY", amount: 1944, qualifiedPercent: 1.0 }
    ],
    narratives: {
      business_component: "AI-assisted commitment-plan generation integrated into the Keep Company platform; includes a PII detection and scrubbing layer for outbound data.",
      permitted_purpose: "Produce psychologically safe, behavior-change-oriented commitment plans at scale; reduce privacy risk when communicating with external AI services.",
      technical_uncertainty: "Could LLMs consistently produce supportive non-directive language? Which prompts and validation rules reliably transform multi-goal commitments? How to detect PII without degrading semantic context?",
      process_of_experimentation: "Prototyped prompt architectures; ran batch generation tests; iterated tone/length/structure; developed multi-goal validation logic; conducted side-by-side output reviews.",
      technological_in_nature: "NLP, prompt engineering with LLMs, validation/rule-based systems, privacy-preserving data handling, API integration.",
      result: "Delivered an AI-assisted plan generation system with PII scrubbing that meaningfully reduces privacy exposure to external AI services."
    },
    notes: []
  },
  {
    id: "p-redesign", name: "Marketing Site Redesign", description: "Visual refresh of the marketing site with new typography and color system. Designer-led project.",
    permittedPurpose: "Improve marketing site visual appeal.",
    technologicalInNature: "Visual design and CSS.",
    technicalUncertainty: "",
    processOfExperimentation: "Iterated on Figma mockups based on team feedback.",
    verdict: "disqualified", confidence: "high",
    hardDisqualifiers: ["aesthetic_only"],
    expenses: [],
    narratives: {},
    notes: []
  }
];
function inferDomain(text) {
  const t = (text || "").toLowerCase();
  if (/(api|software|app|platform|sdk|service|database|llm|ml|frontend|backend|cloud|saas|web)/.test(t))
    return { name: "software", techStack: "software engineering, distributed systems, and computer science",
             alternatives: "competing libraries, architectural patterns, and parameter configurations" };
  if (/(circuit|sensor|firmware|hardware|chip|board|mechanical|robotic|motor|enclosure)/.test(t))
    return { name: "hardware", techStack: "electrical engineering, mechanical engineering, and embedded firmware design",
             alternatives: "component variants, circuit topologies, and material choices" };
  if (/(formulation|chemistry|polymer|coating|reaction|reagent|catalyst|enzyme|assay)/.test(t))
    return { name: "biotech / chemistry", techStack: "organic chemistry, biochemistry, and reaction-pathway design",
             alternatives: "formulations, reaction conditions, and process parameters" };
  if (/(manufacturing|process|throughput|line|fixture|tooling|yield)/.test(t))
    return { name: "process / manufacturing", techStack: "process engineering, statistical process control, and industrial design",
             alternatives: "process configurations, tooling variants, and parameter sweeps" };
  return { name: "software", techStack: "software engineering and computer science",
           alternatives: "competing approaches and configurations" };
}
function draftForProng(prong, ctx) {
  const { projectName, description } = ctx;
  const name = projectName || "this work";
  const domain = inferDomain(`${projectName} ${description}`);
  switch (prong) {
    case "permittedPurpose":
      return `Create a new or improved business component — "${name}" — that ${"[describe the specific function, performance, reliability, or quality improvement targeted]"}. The improvement is concrete and measurable: ${"[add the metric or outcome — e.g. 'reduced p99 latency by 40%', 'increased throughput from X to Y', 'enabled a capability that did not previously exist']"}.`;
    case "technologicalInNature":
      return `The work relies on principles of ${domain.techStack}, including ${"[name the specific technical disciplines and the specific technologies, frameworks, or methods involved]"}. ${"[Confirm this is grounded in hard sciences / engineering rather than social science, art, or routine business analysis.]"}`;
    case "technicalUncertainty":
      return `At the start of the project, it was uncertain whether ${"[describe the specific capability, methodology, or design question that was open at the outset]"}. Publicly available information did not resolve ${"[name the specific gap — e.g. 'whether the new approach would converge under realistic load', 'which of three competing libraries would meet our compliance constraints', 'whether the formulation would remain stable above 60°C']"}.`;
    case "processOfExperimentation":
      return `The team evaluated multiple alternatives by ${"[describe the experimentation method — e.g. 'building parallel prototypes', 'running A/B tests', 'sweeping parameters', 'modeling outcomes']"}, comparing ${domain.alternatives} against measured criteria including ${"[name the metric — e.g. 'latency, accuracy, cost, stability under load']"}. Each iteration informed the next based on observed results.`;
    default:
      return "";
  }
}
function signalForProng(prong, value) {
  const v = (value || "").trim();
  const len = v.length;
  const has = (words) => words.some((w) => v.toLowerCase().includes(w));
  if (prong === "permittedPurpose") {
    if (len === 0) return { score: 0, hint: "Empty. Start by naming the business component being improved." };
    if (len < 30) return { score: 1, hint: "Too short. Name the component and the specific improvement targeted." };
    if (!/improv|new|enabl|reduc|increas|faster|stronger|optim/i.test(v))
      return { score: 2, hint: "Add the specific improvement — what is better after this work?" };
    if (len < 80) return { score: 3, hint: "Almost there. Add a metric or quantified outcome (e.g. 'reduced X by Y%')." };
    if (!/\d/.test(v)) return { score: 4, hint: "Strong. To push to 5, add a quantified outcome (a number, a percentage)." };
    return { score: 5, hint: "Excellent — concrete component, specific improvement, measurable outcome." };
  }
  if (prong === "technologicalInNature") {
    if (len === 0) return { score: 0, hint: "Empty. Name the technical disciplines this work relies on." };
    const hasTech = has([
      "engineering", "software", "computer science", "algorithm", "distributed",
      "machine learning", " ml ", " ai ", "physics", "chemistry", "biology", "hardware",
      "cryptograph", "compiler", "database", "biochemistry", "mechanical", "electrical",
    ]);
    if (!hasTech) return { score: 2, hint: "Add a hard-science / engineering / CS discipline (e.g. 'distributed systems', 'organic chemistry')." };
    if (len < 80) return { score: 4, hint: "Strong on technological grounding. Add the specific framework or library you relied on to push to 5/5." };
    return { score: 5, hint: "Excellent — clear technical disciplines, specific technologies." };
  }
  if (prong === "technicalUncertainty") {
    if (len === 0) return { score: 0, hint: "Empty. What was unknown when you started?" };
    const hasUnc = has(["uncertain", "unclear", "did not know", "didn't know", "could not", "unknown", "open question", "open problem", "feasibility", "unproven", "unresolved"]);
    if (!hasUnc) return { score: 2, hint: "Be explicit about what was unknown at the start. Phrases like 'it was uncertain whether…' or 'unclear how to…' anchor this prong." };
    if (len < 80) return { score: 3, hint: "Almost. Add the specific gap that publicly available information did not resolve." };
    if (!/\bstart|outset|begin|initial/i.test(v))
      return { score: 4, hint: "Strong. To push to 5, anchor that the uncertainty existed at the *start* of the project (not after experimentation began)." };
    return { score: 5, hint: "Excellent — clear, specific uncertainty present at project start." };
  }
  if (prong === "processOfExperimentation") {
    if (len === 0) return { score: 0, hint: "Empty. How did you evaluate alternatives?" };
    const hasExp = has(["tested", "experiment", "iterated", "prototyped", "simulated", "benchmarked", "a/b", "ab test", "trial and error", "measured", "load test", "swept", "compared"]);
    if (!hasExp) return { score: 2, hint: "Describe the experimentation method (modeling, simulation, prototyping, A/B testing, trial & error)." };
    if (!/multiple|alternative|various|several|compared/i.test(v))
      return { score: 3, hint: "Good signal. Add the alternatives you evaluated — the IRS looks for systematic comparison of approaches." };
    if (len < 80) return { score: 4, hint: "Strong. To push to 5, add a measured outcome or metric that informed the next iteration." };
    return { score: 5, hint: "Excellent — systematic process, multiple alternatives, measured outcomes." };
  }
  return { score: 0, hint: "" };
}
function parseTalkItOut(text) {
  const sentences = (text || "").split(/(?<=[.!?])\s+/).filter((s) => s.trim().length > 5);
  const buckets = { permittedPurpose: [], technologicalInNature: [], technicalUncertainty: [], processOfExperimentation: [] };
  for (const s of sentences) {
    const t = s.toLowerCase();
    if (/(uncertain|unclear|did not know|didn't know|wasn't sure|figuring out|unknown|unproven|feasibility|open question)/.test(t))
      buckets.technicalUncertainty.push(s.trim());
    else if (/(tested|tried|prototype|experiment|iterated|benchmarked|measured|load test|a\/b|spike|compared|evaluated|swept)/.test(t))
      buckets.processOfExperimentation.push(s.trim());
    else if (/(framework|language|algorithm|architecture|database|stack|distributed|llm|ml model|library|protocol|microservice)/.test(t))
      buckets.technologicalInNature.push(s.trim());
    else
      buckets.permittedPurpose.push(s.trim());
  }
  return {
    permittedPurpose: buckets.permittedPurpose.join(" "),
    technologicalInNature: buckets.technologicalInNature.join(" "),
    technicalUncertainty: buckets.technicalUncertainty.join(" "),
    processOfExperimentation: buckets.processOfExperimentation.join(" "),
  };
}
function clarifyingQuestion(prong, value) {
  const v = (value || "").trim();
  if (v.length === 0) return null;
  const t = v.toLowerCase();
  if (prong === "permittedPurpose") {
    if (!/\d/.test(v) && /improv|better|faster|reduc|increas/i.test(v))
      return "By how much? A specific number or percentage strengthens this answer.";
    if (v.length < 60)
      return "What specific function, performance, reliability, or quality improvement does this target?";
  }
  if (prong === "technologicalInNature") {
    if (/relies on|uses|based/i.test(v) && !/\b(redis|postgres|react|kafka|python|tensorflow|aws|graphql|rust|java|c\+\+|protobuf)\b/i.test(t))
      return "Which specific frameworks, libraries, or tools are involved?";
  }
  if (prong === "technicalUncertainty") {
    if (/multiple|several|various|many/i.test(v) && !/specifically|for example|e\.g\./i.test(v))
      return "Which uncertainties specifically? Listing 2–3 named gaps makes this much stronger.";
    if (!/\b(at the start|outset|begin|initially)\b/i.test(t) && v.length > 50)
      return "Was this uncertainty present at the start of the project? Anchoring it to the outset matters under §41.";
  }
  if (prong === "processOfExperimentation") {
    if (/multiple|alternative|several/i.test(v) && !/\b(specifically|named|for example|e\.g\.)\b/i.test(t))
      return "Which alternatives did you compare specifically? Naming 2–3 strengthens this answer.";
    if (!/\b(measured|metric|benchmark|p99|p95|latency|accuracy|throughput|yield|stability|score)\b/i.test(t))
      return "What metric told you one alternative was better than another?";
  }
  return null;
}
const EXAMPLES = {
  permittedPurpose: [
    { domain: "Software", text: "Create a new payment-routing service that reduces failed-payment retries by 60% and lowers p99 latency from 800ms to under 200ms across all merchant tiers." },
    { domain: "Hardware", text: "Develop a new battery management board that extends operational range by 25% while reducing thermal throttling events under sustained load." },
    { domain: "Biotech", text: "Develop a polymer coating formulation that remains stable above 60°C while preserving the substrate's tensile strength, enabling deployment in environments where prior formulations failed." },
  ],
  technologicalInNature: [
    { domain: "Software", text: "Relies on distributed systems, queuing theory, and database engineering — specifically Kafka for event streaming, Postgres logical replication, and Raft consensus for failover coordination." },
    { domain: "Hardware", text: "Relies on electrical engineering and embedded firmware design — buck-boost converter topology, ARM Cortex-M firmware for real-time current monitoring, and PCB layout optimized for thermal dissipation." },
    { domain: "Biotech", text: "Relies on polymer chemistry and surface science — specifically silane-coupling agents, cross-linking reaction kinetics, and contact-angle measurement under controlled humidity." },
  ],
  technicalUncertainty: [
    { domain: "Software", text: "At the start of the project, it was uncertain whether per-merchant routing rules could be applied with sub-50ms latency overhead, and which database isolation level would prevent double-charge under concurrent retries. Public Postgres docs did not address our specific concurrency pattern." },
    { domain: "Hardware", text: "It was uncertain at the outset whether the proposed buck-boost topology could maintain 92% efficiency at low load without inducing audible coil whine, and whether the firmware ADC sampling rate could keep up with transient load spikes." },
    { domain: "Biotech", text: "At project start, it was unclear whether the chosen cross-linking density would yield acceptable mechanical strength without losing optical clarity, and whether silane-coupling agents alone could achieve target adhesion on the new substrate." },
  ],
  processOfExperimentation: [
    { domain: "Software", text: "Built three parallel prototypes — one using SERIALIZABLE isolation with optimistic retry, one using row-level advisory locks, and one using a Redis-based dedupe layer in front of Postgres. Ran each under synthetic load (10K requests/min, simulated network jitter) and measured retry rate, p99 latency, and database CPU. The advisory-lock approach won on latency but failed under prolonged spikes, so we iterated to a hybrid design." },
    { domain: "Hardware", text: "Built three PCB revisions varying inductor selection and thermal-pad configuration; measured efficiency at six load points and coil whine at two ambient temperatures. Iterated firmware sampling rate across 4kHz, 8kHz, and 16kHz to find the threshold where transient detection was reliable without overloading the MCU." },
    { domain: "Biotech", text: "Synthesized five formulation variants sweeping cross-linker concentration (1%, 2.5%, 5%, 7.5%, 10%) and characterized each via tensile testing, DSC, and contact-angle measurement. Two formulations passed initial screening; we then ran 1,000-hour humidity aging on those two and selected the variant with the lower swell ratio." },
  ],
};
const fmtMoney = (n) => "$" + Math.round(n).toLocaleString();
const totalQREForProject = (p) => p.expenses.reduce((s, e) => {
  const base = e.amount * e.qualifiedPercent;
  return s + (e.category === "contractor" ? base * 0.65 : base);
}, 0);
const sumQRE = (projects) => projects.reduce((s, p) => s + totalQREForProject(p), 0);
const VERDICT_LABEL = { qualified: "Qualified", borderline: "Borderline", disqualified: "Likely Disqualified", pending: "Pending review" };
const VERDICT_CLASS = { qualified: "badge-qualified", borderline: "badge-borderline", disqualified: "badge-disqualified", pending: "badge-pending" };
const PRONG_LABEL = {
  permitted_purpose: "Purpose",
  technological:     "Technological",
  uncertainty:       "Uncertainty",
  experimentation:   "Experimentation"
};
const { useState, useMemo } = React;
function VerdictBadge({ verdict }) {
  return <span className={"badge " + (VERDICT_CLASS[verdict] || "badge-pending")}>{VERDICT_LABEL[verdict] || verdict}</span>;
}
function Header({ user, onSignOut, onNav, currentPage }) {
  const isAdmin = user.role === "windstone_admin";
  return (
    <header className="border-b border-line bg-white">
      <div className="mx-auto max-w-6xl flex items-center justify-between px-6 py-3">
        <button onClick={() => onNav(isAdmin ? "admin-rollup" : "contributor-list")} className="flex items-center gap-2.5">
          <div className="h-8 w-8 rounded bg-navy-600 flex items-center justify-center text-white text-sm font-bold">W</div>
          <span className="text-lg font-semibold text-navy-600 tracking-tight">Windstone Financial</span>
        </button>
        <nav className="flex items-center gap-1">
          {isAdmin ? (
            <button className="btn-ghost" onClick={() => onNav("admin-rollup")}>Engagements</button>
          ) : (
            <>
              <button className="btn-ghost" onClick={() => onNav("contributor-list")}>Projects</button>
              <button className="btn-ghost" onClick={() => onNav("new-project")}>Start a project</button>
            </>
          )}
          <button className="btn-ghost" onClick={onSignOut}>Sign out · {user.name}</button>
        </nav>
      </div>
    </header>
  );
}
function Landing({ onSignIn }) {
  const [email, setEmail] = useState("");
  const [error, setError] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [stage, setStage] = useState("form");
  const [sentEmail, setSentEmail] = useState("");
  const [resendCooldown, setResendCooldown] = useState(0);
  const isDev = typeof window !== "undefined" && (
    window.location.hostname === "localhost" ||
    window.location.search.includes("dev=1")
  );

  React.useEffect(() => {
    if (resendCooldown <= 0) return;
    const t = setTimeout(() => setResendCooldown(resendCooldown - 1), 1000);
    return () => clearTimeout(t);
  }, [resendCooldown]);

  const emailIsValid = (e) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e);

  async function requestLink(e) {
    if (e) e.preventDefault();
    if (submitting) return;
    const normalized = email.trim().toLowerCase();
    if (!normalized) { setError("Enter your email to continue."); return; }
    if (!emailIsValid(normalized)) { setError("Enter a valid email address."); return; }
    setError("");
    setSubmitting(true);
    await new Promise(r => setTimeout(r, 400));
    setSentEmail(normalized);
    setStage("sent");
    setResendCooldown(30);
    setSubmitting(false);
  }

  async function resendLink() {
    if (resendCooldown > 0 || submitting) return;
    setSubmitting(true);
    await new Promise(r => setTimeout(r, 400));
    setResendCooldown(30);
    setSubmitting(false);
  }

  function openMagicLink() {
    const user = Object.values(USERS).find(u => u.email.toLowerCase() === sentEmail);
    if (!user) {
      setStage("form");
      setError("This email isn't associated with a Windstone account.");
      return;
    }
    onSignIn(user);
  }

  function useDifferentEmail() {
    setStage("form");
    setError("");
    setSubmitting(false);
  }

  function useDemoAccount(demoEmail) {
    setEmail(demoEmail);
    setError("");
    if (stage === "sent") setStage("form");
  }

  function roleLabel(role) {
    if (role === "windstone_admin") return "Windstone Admin";
    if (role === "tenant_admin") return "Tenant Admin";
    return "Contributor";
  }

  return (
    <main className="min-h-screen grid grid-cols-1 lg:grid-cols-[7fr_5fr]">
      <div className="flex items-center justify-center px-6 sm:px-10 lg:px-16 pt-10 pb-6 lg:py-16 lg:border-r lg:border-line">
        <div className="w-full max-w-md">
          <div className="flex items-center gap-2.5 mb-10">
            <div className="h-8 w-8 rounded bg-navy-600 flex items-center justify-center text-white text-sm font-bold">W</div>
            <span className="text-lg font-semibold text-navy-600 tracking-tight">Windstone Financial</span>
          </div>
          <div className="h-0.5 w-10 bg-teal-500 mb-5" aria-hidden="true"></div>
          <h1 className="text-3xl sm:text-4xl font-semibold text-navy-600 tracking-tight leading-[1.15] mb-5">
            R&amp;D Tax Credit Documentation
          </h1>
          <p className="text-sm sm:text-base text-ink-600 leading-relaxed">
            Capture qualifying projects, technical uncertainty, experimentation, and supporting evidence as the work happens.
          </p>
        </div>
      </div>

      <div className="flex items-center justify-center px-6 sm:px-10 lg:px-16 pt-4 pb-10 lg:py-16">
        <div className="w-full max-w-[420px]">
          {stage === "form" && (
            <>
              <div className="mb-7">
                <h2 className="text-2xl font-semibold text-ink-900 tracking-tight">Welcome back</h2>
                <p className="mt-2 text-sm text-ink-600 leading-relaxed">
                  Sign in to continue documenting and supporting your R&amp;D tax credit.
                </p>
              </div>

              <form onSubmit={requestLink} noValidate className="space-y-4">
                <div>
                  <label htmlFor="email" className="block text-sm font-medium text-ink-900 mb-1.5">Email</label>
                  <input
                    id="email"
                    type="email"
                    autoComplete="email"
                    autoFocus
                    value={email}
                    onChange={(e) => { setEmail(e.target.value); if (error) setError(""); }}
                    placeholder="you@company.com"
                    aria-invalid={error ? "true" : "false"}
                    aria-describedby={error ? "email-error" : undefined}
                    disabled={submitting}
                    className="input"
                  />
                  {error && (
                    <p id="email-error" role="alert" className="mt-1.5 flex items-start gap-1.5 text-xs text-rose-700">
                      <span aria-hidden="true" className="font-bold">!</span>
                      <span>{error}</span>
                    </p>
                  )}
                </div>
                <button
                  type="submit"
                  disabled={submitting}
                  aria-busy={submitting ? "true" : "false"}
                  className="btn-primary w-full"
                >
                  {submitting ? "Sending link…" : "Continue"}
                </button>
                <p className="text-xs text-ink-400 text-center leading-relaxed">
                  We&rsquo;ll email you a secure sign-in link. No password required.
                </p>
              </form>
            </>
          )}

          {stage === "sent" && (
            <>
              <div className="mb-6">
                <div className="inline-flex items-center justify-center h-10 w-10 rounded-lg bg-teal-50 ring-1 ring-teal-100 mb-4 text-teal-700">
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                    <rect x="3" y="5" width="18" height="14" rx="2"/>
                    <path d="M3 7l9 6 9-6"/>
                  </svg>
                </div>
                <h2 className="text-2xl font-semibold text-ink-900 tracking-tight">Check your email</h2>
                <p className="mt-2 text-sm text-ink-600 leading-relaxed">
                  We sent a sign-in link to <span className="font-semibold text-ink-900 break-all">{sentEmail}</span>. Open it in this browser to continue.
                </p>
              </div>

              <p className="text-xs text-ink-600 leading-relaxed">
                The link expires in 15 minutes. Didn&rsquo;t get it?{" "}
                <button
                  type="button"
                  onClick={resendLink}
                  disabled={resendCooldown > 0 || submitting}
                  className="text-navy-600 font-medium hover:underline disabled:text-ink-400 disabled:no-underline disabled:cursor-not-allowed"
                >
                  {submitting ? "Sending…" : resendCooldown > 0 ? `Resend in ${resendCooldown}s` : "Resend link"}
                </button>{" "}or{" "}
                <button
                  type="button"
                  onClick={useDifferentEmail}
                  className="text-navy-600 font-medium hover:underline"
                >
                  use a different email
                </button>.
              </p>

              <div className="mt-8 rounded-md border border-dashed border-line bg-cream-50 p-4">
                <p className="text-[10px] uppercase tracking-[0.14em] font-semibold text-ink-400 mb-2">Prototype</p>
                <button
                  type="button"
                  onClick={openMagicLink}
                  className="btn-primary w-full"
                >
                  Open sign-in link
                </button>
                <p className="text-xs text-ink-600 mt-2 leading-relaxed">
                  Simulates clicking the link in the email. Replace with real email delivery before production.
                </p>
              </div>
            </>
          )}

          {isDev && stage === "form" && (
            <details className="mt-8">
              <summary className="text-xs text-ink-400 cursor-pointer hover:text-ink-600 select-none">
                Development test accounts
              </summary>
              <div className="mt-3 divide-y divide-line rounded-md border border-line bg-white overflow-hidden">
                {Object.values(USERS).map(u => (
                  <button
                    key={u.id}
                    type="button"
                    onClick={() => useDemoAccount(u.email)}
                    className="w-full text-left px-3 py-2 hover:bg-cream-50"
                  >
                    <div className="font-mono text-xs text-ink-900">{u.email}</div>
                    <div className="text-[11px] text-ink-400 mt-0.5">{roleLabel(u.role)}</div>
                  </button>
                ))}
              </div>
            </details>
          )}
        </div>
      </div>
    </main>
  );
}
function ContributorList({ projects, user, onOpenProject, onNew }) {
  return (
    <div>
      <div className="flex items-end justify-between mb-6">
        <div>
          <p className="text-xs uppercase tracking-[0.14em] font-semibold text-ink-400">{ENGAGEMENT.clientName} · Tax Year {ENGAGEMENT.taxYear}</p>
          <h1 className="mt-1 text-2xl sm:text-3xl font-semibold text-ink-900 tracking-tight">Your R&amp;D projects</h1>
        </div>
        <button className="btn-primary" onClick={onNew}>Start a project</button>
      </div>
      <div className="card divide-y divide-line">
        {projects.length === 0 ? (
          <div className="p-10 text-center text-sm text-ink-600">No projects yet. Start a project to begin documenting your R&amp;D activity.</div>
        ) : projects.map((p) => (
          <button key={p.id} onClick={() => onOpenProject(p.id)} className="w-full text-left flex items-start justify-between gap-6 p-5 hover:bg-cream-50">
            <div>
              <div className="flex items-center gap-3">
                <h3 className="font-semibold text-ink-900">{p.name}</h3>
                <VerdictBadge verdict={p.verdict} />
              </div>
              <p className="mt-1 line-clamp-2 max-w-2xl text-sm text-ink-600">{p.description}</p>
            </div>
            <div className="shrink-0 text-right text-xs text-ink-400">
              <div>{fmtMoney(totalQREForProject(p))} captured QRE</div>
              <div className="mt-1">{p.notes.length} notes · {p.expenses.length} expenses</div>
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}
function FieldArea({ name, label, hint, required, rows = 3, value, onChange }) {
  return (
    <label className="block">
      <span className="text-sm font-medium text-ink-900">
        {label}{required && <span className="ml-0.5 text-rose-600">*</span>}
      </span>
      {hint && <p className="mt-1 text-xs text-ink-600">{hint}</p>}
      <textarea name={name} rows={rows} required={required} value={value} onChange={onChange} className="input mt-1.5" />
    </label>
  );
}
function ScoreBar({ score }) {
  const pct = (score / 5) * 100;
  const color = score <= 2 ? "bg-rose-400" : score === 3 ? "bg-amber-400" : "bg-emerald-500";
  return (
    <div className="h-1.5 w-24 rounded-full bg-line overflow-hidden">
      <div className={`h-full ${color}`} style={{ width: `${pct}%` }} />
    </div>
  );
}
function EnhancedField({ prong, label, hint, rows = 4, value, onChange, projectName, description }) {
  const [showExamples, setShowExamples] = useState(false);
  const signal = useMemo(() => signalForProng(prong, value), [prong, value]);
  const clarify = useMemo(() => clarifyingQuestion(prong, value), [prong, value]);
  const examples = EXAMPLES[prong] || [];
  function draft() {
    const d = draftForProng(prong, { projectName, description });
    if (!value || value.trim().length === 0 || confirm("Replace current content with an AI draft?")) {
      onChange({ target: { value: d } });
    }
  }
  function useExample(text) { onChange({ target: { value: text } }); setShowExamples(false); }
  return (
    <div className="block">
      <div className="flex items-start justify-between gap-3">
        <div className="flex-1">
          <span className="text-sm font-medium text-ink-900">{label}</span>
          {hint && <p className="mt-1 text-xs text-ink-600">{hint}</p>}
        </div>
        <div className="flex items-center gap-2 shrink-0">
          <button type="button" onClick={draft} className="btn-secondary text-xs" title="Generate a starting draft from the project name and description">
            ✨ Draft with AI
          </button>
          <button type="button" onClick={() => setShowExamples(!showExamples)} className="btn-ghost text-xs">
            {showExamples ? "Hide examples ▴" : "Show examples ▾"}
          </button>
        </div>
      </div>
      {showExamples && (
        <div className="mt-2 space-y-2 rounded-md border border-line bg-cream-50 p-3">
          <p className="text-xs font-medium text-ink-600">Click any example to use it as a starting point:</p>
          {examples.map((ex, i) => (
            <button key={i} type="button" onClick={() => useExample(ex.text)} className="block w-full text-left rounded border border-line bg-white p-2 text-xs hover:border-navy-600">
              <div className="text-[10px] uppercase tracking-wider text-ink-400">{ex.domain}</div>
              <div className="mt-1 text-ink-900">{ex.text}</div>
            </button>
          ))}
        </div>
      )}
      <textarea
        rows={rows}
        value={value}
        onChange={onChange}
        className="input mt-2"
        placeholder={`Type here, or click 'Draft with AI' for a starting paragraph based on ${projectName ? `"${projectName}"` : "your project"}.`}
      />
      {}
      <div className="mt-2 flex flex-wrap items-start gap-2">
        {signal.score > 0 && (
          <div className="inline-flex items-center gap-2 rounded-md border border-line bg-white px-2 py-1 text-xs">
            <ScoreBar score={signal.score} />
            <span className="font-mono font-semibold text-ink-900">{signal.score}/5</span>
            <span className="text-ink-600">·</span>
            <span className="text-ink-600">{signal.hint}</span>
          </div>
        )}
        {signal.score === 0 && value === "" && (
          <div className="inline-flex items-center gap-2 rounded-md border border-line bg-cream-50 px-2 py-1 text-xs text-ink-600">
            <span>Live quality signal appears as you type</span>
          </div>
        )}
        {clarify && (
          <div className="inline-flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 px-2 py-1 text-xs text-amber-900">
            <span className="font-semibold">Clarify:</span>
            <span>{clarify}</span>
          </div>
        )}
      </div>
    </div>
  );
}
function TalkItOutSection({ projectName, description, onApply }) {
  const [open, setOpen] = useState(false);
  const [text, setText] = useState("");
  function generate() {
    if (!text.trim()) return;
    const split = parseTalkItOut(text);
    const finalForm = {
      permittedPurpose: split.permittedPurpose || draftForProng("permittedPurpose", { projectName, description }),
      technologicalInNature: split.technologicalInNature || draftForProng("technologicalInNature", { projectName, description }),
      technicalUncertainty: split.technicalUncertainty || draftForProng("technicalUncertainty", { projectName, description }),
      processOfExperimentation: split.processOfExperimentation || draftForProng("processOfExperimentation", { projectName, description }),
    };
    onApply(finalForm);
  }
  return (
    <div className="rounded-md border border-navy-600/20 bg-navy-600/[0.03] p-4">
      <button type="button" onClick={() => setOpen(!open)} className="w-full text-left flex items-center justify-between">
        <div>
          <div className="text-sm font-semibold text-navy-600">✨ Talk it out — let AI fill all four prongs</div>
          <div className="mt-0.5 text-xs text-ink-600">
            Describe what you were working on in plain English. AI splits it into the four §41 fields, which you then edit.
          </div>
        </div>
        <span className="text-navy-600">{open ? "▴" : "▾"}</span>
      </button>
      {open && (
        <div className="mt-3 space-y-2">
          <textarea
            rows={5}
            value={text}
            onChange={(e) => setText(e.target.value)}
            className="input"
            placeholder="What were you trying to do? What was unknown when you started? What did you try? What did you measure? What did you learn?"
          />
          <div className="flex items-center justify-end gap-2">
            <button type="button" className="btn-ghost text-xs" onClick={() => setText("")}>Clear</button>
            <button type="button" className="btn-primary text-xs" onClick={generate}>
              Generate all four prongs
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
