"use client";

import { useEffect, useMemo, useState } from "react";
import { audits as initialAudits, cqcKeys, frequencies, type AuditItem, type AuditStatus, type CqcKey } from "./audit-data";

type Rating = "met" | "partial" | "not-met" | "na";
type Answer = { rating?: Rating; comment?: string; action?: string; resident?: string };
type Resident = { id: string; initials: string; room: string };
type Question = { id: string; text: string; regulation: string };
type Section = { title: string; questions: Question[] };
type Screen = "dashboard" | "settings" | "audit";

const sections: Section[] = [
  { title: "Assessment and person-centred planning", questions: [
    { id:"A1", text:"Is there a current, comprehensive assessment covering physical, mental, emotional and social needs, communication, protected characteristics, preferences, strengths and desired outcomes?", regulation:"Regulation 9 · Assessing needs · Treating people as individuals" },
    { id:"A2", text:"Does the care plan clearly describe what matters to the person, their usual routines, choices, cultural or religious needs, relationships, identity and how staff should support these?", regulation:"Regulations 9 and 10" },
    { id:"A3", text:"Are agreed goals and outcomes specific to the person, realistic and reflected in day-to-day support?", regulation:"Regulation 9" },
    { id:"A4", text:"Does the plan promote independence, choice and control, including what the person can do for themselves and the least restrictive support required?", regulation:"Regulation 9 · Mental Capacity Act 2005" },
    { id:"A5", text:"Are communication needs and accessible-information arrangements recorded clearly and used in practice?", regulation:"Regulation 9 · Equality Act 2010" },
    { id:"A6", text:"Is the care plan available to staff who need it, and do staff records show they know about relevant changes?", regulation:"Regulations 9 and 17" },
  ]},
  { title: "Involvement, consent and lawful decision-making", questions: [
    { id:"B1", text:"Is there evidence that the person was actively involved in assessment, planning and review to the maximum extent possible?", regulation:"Regulation 9 · Listening to and involving people" },
    { id:"B2", text:"Where appropriate, is involvement of family, an advocate, attorney, deputy or other lawful representative recorded, with the basis of their authority clear?", regulation:"Regulations 9 and 11 · Mental Capacity Act 2005" },
    { id:"B3", text:"Is consent to care and treatment current, decision-specific where needed, freely given and recorded, including any refusal or withdrawal?", regulation:"Regulation 11" },
    { id:"B4", text:"Where capacity may be in doubt, is a decision-specific capacity assessment recorded after practicable support was provided?", regulation:"Regulation 11 · Mental Capacity Act 2005 sections 1-3" },
    { id:"B5", text:"Where the person lacks capacity, does the record show a lawful, person-centred best-interests process, consultation and consideration of less restrictive options?", regulation:"Mental Capacity Act 2005 sections 1 and 4 · Regulations 9 and 11" },
    { id:"B6", text:"Do any restrictions or continuous supervision arrangements correspond with lawful authorisation and the care plan, with conditions and review dates recorded?", regulation:"Mental Capacity Act 2005 / DoLS · Regulations 11-13" },
  ]},
  { title: "Risk assessment and safety planning", questions: [
    { id:"C1", text:"Are all reasonably foreseeable individual risks assessed, including falls, mobility, pressure damage, nutrition, hydration, choking, medicines, distress, infection, fire evacuation and missing person risk where relevant?", regulation:"Regulation 12" },
    { id:"C2", text:"Are risk assessments current, individualised, completed by competent staff and proportionate to the person's needs?", regulation:"Regulation 12" },
    { id:"C3", text:"Does each identified risk have clear control measures, escalation thresholds and staff actions that balance safety with rights, preferences and positive risk-taking?", regulation:"Regulation 12 · Mental Capacity Act 2005" },
    { id:"C4", text:"Are risk ratings and control measures consistent across the assessment, care plan, PEEP, charts and other linked records?", regulation:"Regulations 12 and 17" },
    { id:"C5", text:"Have changes, incidents, near misses, hospital visits or professional recommendations resulted in timely reassessment and care-plan updates?", regulation:"Regulations 9, 12 and 17" },
    { id:"C6", text:"Where care is shared or transferred, is there evidence of timely information-sharing and coordinated planning to protect the person?", regulation:"Regulation 12(2)(i)" },
  ]},
  { title: "Daily records and delivery of care", questions: [
    { id:"D1", text:"Are daily entries contemporaneous, dated and timed, attributable, legible, factual and sufficiently detailed to show the care and support actually provided?", regulation:"Regulation 17(2)(c)" },
    { id:"D2", text:"Do daily records reflect the person's choices, mood, wellbeing, engagement, outcomes and any care declined, rather than only task completion?", regulation:"Regulations 9 and 17" },
    { id:"D3", text:"Do records show that planned monitoring and interventions were completed at the required frequency, with gaps explained and followed up?", regulation:"Regulations 12 and 17" },
    { id:"D4", text:"Are changes from baseline, deterioration, pain, distress or new risks recognised, escalated promptly and followed through to an outcome?", regulation:"Regulations 12 and 17" },
    { id:"D5", text:"Are appointments, referrals, clinical advice and recommendations recorded and incorporated into the care plan when relevant?", regulation:"Regulations 9, 12 and 17" },
    { id:"D6", text:"Is there consistency between daily notes and linked records such as food/fluid, weight, repositioning, bowel, wound, behaviour and incident charts?", regulation:"Regulation 17" },
  ]},
  { title: "Review, outcomes and record governance", questions: [
    { id:"E1", text:"Has the care plan and each risk assessment been reviewed at the planned frequency and sooner when needs, wishes or risks changed?", regulation:"Regulations 9, 12 and 17" },
    { id:"E2", text:"Do reviews evaluate whether support is working, using the person's experience, outcomes, incidents, trends and professional input rather than merely restating the plan?", regulation:"Regulation 17 · Monitoring and improving outcomes" },
    { id:"E3", text:"Are changes to the plan clearly dated, authorised, communicated and reflected in current staff instructions, with obsolete versions controlled?", regulation:"Regulations 9 and 17" },
    { id:"E4", text:"Are records accurate, complete, secure, confidential and accessible only to authorised people who need them to provide safe care?", regulation:"Regulation 17 · Data Protection Act 2018 / UK GDPR" },
    { id:"E5", text:"Are corrections and late entries transparent, traceable and made according to policy, without obscuring the original record?", regulation:"Regulation 17" },
    { id:"E6", text:"Does the sampled evidence show that each person receives care consistent with the current plan, with unexplained omissions or recurring shortfalls addressed?", regulation:"Regulations 9, 12 and 17" },
  ]},
];

const allQuestions = sections.flatMap(s => s.questions);
const ratingOptions: Array<{value:Rating; label:string; points:number}> = [
  {value:"met",label:"Met",points:80}, {value:"partial",label:"Partially met",points:40},
  {value:"not-met",label:"Not met",points:20}, {value:"na",label:"N/A",points:0},
];
const statusLabels: Record<AuditStatus,string> = {completed:"Completed",overdue:"Overdue","due-soon":"Due within 7 days","not-due":"Not currently due"};

function Brand(){return <div className="brand"><img className="brand-logo" src="/meadowbanks-logo-cream.png" alt="Meadowbanks Care Home"/></div>}

function Ring({value, tone="blue"}:{value:number;tone?:string}){
  return <div className={`ring ${tone}`} style={{"--value":`${value*3.6}deg`} as React.CSSProperties}><div><strong>{value}%</strong><span>currently</span></div></div>;
}

export default function Home(){
  const [screen,setScreen]=useState<Screen>("dashboard");
  const [audits,setAudits]=useState<AuditItem[]>(initialAudits);
  const [selected,setSelected]=useState<AuditItem>(initialAudits[0]);
  const [readOnly,setReadOnly]=useState(false);
  const [search,setSearch]=useState("");
  const [filter,setFilter]=useState("All statuses");

  useEffect(()=>{fetch("/api/audits").then(async response=>{if(!response.ok)throw new Error("Unable to load audits");return response.json() as Promise<AuditItem[]>}).then(setAudits).catch(error=>console.error(error));},[]);

  const counts=useMemo(()=>({
    completed:audits.filter(a=>a.status==="completed").length,
    overdue:audits.filter(a=>a.status==="overdue").length,
    dueSoon:audits.filter(a=>a.status==="due-soon").length,
    notDue:audits.filter(a=>a.status==="not-due").length,
  }),[audits]);
  const visible=audits.filter(a=>(filter==="All statuses"||(filter==="In progress"?a.draft&&a.status!=="completed":statusLabels[a.status]===filter))&&(`${a.name} ${a.department}`.toLowerCase().includes(search.toLowerCase()))).sort((a,b)=>{const rank=(item:AuditItem)=>item.status==="overdue"?0:item.status==="due-soon"?1:item.draft&&item.status!=="completed"?2:item.status==="completed"?3:4;return rank(a)-rank(b)||a.id-b.id});
  const openAudit=(audit:AuditItem,view:boolean)=>{setSelected(audit);setReadOnly(view);setScreen("audit");window.scrollTo(0,0)};
  const updateSetting=(id:number,patch:Partial<AuditItem>)=>{setAudits(prev=>prev.map(a=>a.id===id?{...a,...patch}:a));fetch("/api/audits",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({id,patch})}).then(response=>{if(!response.ok)throw new Error("Unable to save audit settings")}).catch(error=>{console.error(error);window.alert("The setting could not be saved to the central database.")})};

  return <main>
    <header className="topbar">
      <Brand/>
      <nav className="main-nav" aria-label="Primary navigation">
        <button className={screen==="dashboard"?"active":""} onClick={()=>setScreen("dashboard")}>Dashboard</button>
        <button className={screen==="settings"?"active":""} onClick={()=>setScreen("settings")}>Audit settings</button>
      </nav>
      <div className="account"><span>TB</span><div><strong>Administrator</strong><small>contact@meadowbanks.co.uk</small></div></div>
    </header>
    {screen==="dashboard"&&<Dashboard audits={visible} allCount={audits.length} counts={counts} search={search} setSearch={setSearch} filter={filter} setFilter={setFilter} openAudit={openAudit}/>} 
    {screen==="settings"&&<Settings audits={audits} update={updateSetting}/>} 
    {screen==="audit"&&<AuditWorkspace audit={selected} readOnly={readOnly} onBack={()=>setScreen("dashboard")} onDraftSaved={(id)=>setAudits(prev=>prev.map(a=>a.id===id?{...a,draft:a.status!=="completed"}:a))} onCompleted={(id,score)=>setAudits(prev=>prev.map(a=>a.id===id?{...a,draft:false,status:"completed",due:"Completed",score}:a))}/>} 
  </main>;
}

function Dashboard({audits,allCount,counts,search,setSearch,filter,setFilter,openAudit}:{audits:AuditItem[];allCount:number;counts:{completed:number;overdue:number;dueSoon:number;notDue:number};search:string;setSearch:(v:string)=>void;filter:string;setFilter:(v:string)=>void;openAudit:(a:AuditItem,v:boolean)=>void}){
  const categoryScores: Array<[CqcKey,number,string]>=[["Safe",72,"green"],["Effective",68,"blue"],["Caring",80,"green"],["Responsive",64,"blue"],["Well-led",60,"amber"]];
  return <div className="page-wrap">
    <section className="page-heading">
      <div><p className="eyebrow">QUALITY ASSURANCE</p><h1>Audit programme</h1><p>One place to review every required audit, upcoming deadline and internal assurance score.</p></div>
      <div className="programme-chip"><span>2026 programme</span><strong>{counts.completed} of {allCount} complete</strong></div>
    </section>
    <section className="summary-grid" aria-label="Audit status summary">
      <SummaryCard label="Completed" value={counts.completed} note="Audits recorded" tone="green"/>
      <SummaryCard label="Overdue" value={counts.overdue} note="Require attention" tone="red"/>
      <SummaryCard label="Due within 7 days" value={counts.dueSoon} note="Plan this week" tone="amber"/>
      <SummaryCard label="Not currently due" value={counts.notDue} note="Scheduled ahead" tone="grey"/>
    </section>
    <section className="panel assurance-panel">
      <div className="panel-title"><div><p className="eyebrow">INTERNAL ASSURANCE</p><h2>CQC key questions</h2></div><p>Scores use Met 80% · Partially met 40% · Not met 20%</p></div>
      <div className="dial-grid">{categoryScores.map(([name,value,tone])=><article className="dial-card" key={name}><div className="dial-top"><h3>{name}</h3></div><Ring value={value} tone={tone}/><div className="dial-counts"><span>Met <b>{Math.round(value/4)}</b></span><span>Partial <b>{Math.max(1,Math.round((80-value)/8))}</b></span><span>Not met <b>{value<65?2:1}</b></span></div></article>)}</div>
      <p className="assurance-note">These are Meadowbanks internal assurance scores and are not official CQC ratings.</p>
    </section>
    <section className="panel audit-panel">
      <div className="panel-title list-title"><div><p className="eyebrow">FULL PROGRAMME</p><h2>All audits <span>{allCount}</span></h2></div><div className="table-tools"><label className="search"><span>⌕</span><input aria-label="Search audits" placeholder="Search audits" value={search} onChange={e=>setSearch(e.target.value)}/></label><select aria-label="Filter by status" value={filter} onChange={e=>setFilter(e.target.value)}><option>All statuses</option><option>In progress</option>{Object.values(statusLabels).map(x=><option key={x}>{x}</option>)}</select></div></div>
      <div className="table-scroll"><table className="audit-table"><thead><tr><th>Audit</th><th>CQC key question</th><th>Frequency</th><th>Next due</th><th>Status</th><th>Score</th><th><span className="sr-only">Actions</span></th></tr></thead><tbody>{audits.map(a=><tr key={a.id}><td><strong>{a.name}</strong><small>{a.department}</small></td><td><span className="cqc-tag">{a.cqc}</span></td><td>{a.frequency}</td><td>{a.due}</td><td><div className="status-stack"><span className={`status ${a.status}`}><i/>{statusLabels[a.status]}</span>{a.draft&&a.status!=="completed"&&<span className="substatus">In progress</span>}</div></td><td className="score-cell">{a.score!==undefined?`${a.score}%`:'—'}</td><td><div className="row-actions"><button onClick={()=>openAudit(a,true)}>View</button><button className="edit" onClick={()=>openAudit(a,false)}>Edit</button></div></td></tr>)}</tbody></table></div>
    </section>
  </div>;
}

function SummaryCard({label,value,note,tone}:{label:string;value:number;note:string;tone:string}){return <article className={`summary-card ${tone}`}><div className="summary-icon"><i/></div><div><span>{label}</span><strong>{value}</strong><small>{note}</small></div></article>}

function Settings({audits,update}:{audits:AuditItem[];update:(id:number,p:Partial<AuditItem>)=>void}){
  return <div className="page-wrap">
    <section className="page-heading"><div><p className="eyebrow">ADMINISTRATION</p><h1>Audit settings</h1><p>Set the CQC key question and required frequency for every audit in the programme.</p></div><div className="programme-chip"><span>Audit catalogue</span><strong>{audits.length} required audits</strong></div></section>
    <div className="settings-callout"><strong>Changes save automatically</strong><span>The next due date will be recalculated from the selected frequency after the current audit is completed.</span></div>
    <section className="panel settings-panel"><div className="table-scroll"><table className="settings-table"><thead><tr><th>Department</th><th>Audit name</th><th>CQC key question</th><th>Frequency</th><th>Next due</th></tr></thead><tbody>{audits.map(a=><tr key={a.id}><td>{a.department}</td><td><strong>{a.name}</strong></td><td><select aria-label={`CQC key question for ${a.name}`} value={a.cqc} onChange={e=>update(a.id,{cqc:e.target.value as CqcKey})}>{cqcKeys.map(x=><option key={x}>{x}</option>)}</select></td><td><select aria-label={`Frequency for ${a.name}`} value={frequencies.includes(a.frequency)?a.frequency:"Monthly"} onChange={e=>update(a.id,{frequency:e.target.value})}>{frequencies.map(x=><option key={x}>{x}</option>)}</select></td><td>{a.due}</td></tr>)}</tbody></table></div></section>
  </div>;
}

function AuditWorkspace({audit,readOnly,onBack,onDraftSaved,onCompleted}:{audit:AuditItem;readOnly:boolean;onBack:()=>void;onDraftSaved:(id:number)=>void;onCompleted:(id:number,score:number)=>void}){
  const [answers,setAnswers]=useState<Record<string,Answer>>({});
  const [residents,setResidents]=useState<Resident[]>([{id:"1",initials:"GL",room:"05"},{id:"2",initials:"MP",room:"12"},{id:"3",initials:"RS",room:"08"}]);
  const [initials,setInitials]=useState(""); const [room,setRoom]=useState("");
  const [auditor,setAuditor]=useState("Taja Borley");
  const [date,setDate]=useState("2026-08-09");
  const [hydrated,setHydrated]=useState(false);
  const [dirty,setDirty]=useState(false);
  const answered=Object.values(answers).filter(a=>a.rating).length;
  const scored=Object.values(answers).filter(a=>a.rating&&a.rating!=="na");
  const score=scored.length?Math.round(scored.reduce((sum,a)=>sum+(ratingOptions.find(r=>r.value===a.rating)?.points||0),0)/scored.length):0;
  useEffect(()=>{setHydrated(false);fetch(`/api/audits/${audit.id}`).then(async response=>{if(!response.ok)throw new Error("Unable to load audit record");return response.json()}).then(data=>{if(data){setAnswers(data.answers||{});setResidents(data.residents||[]);setAuditor(data.auditor||"");setDate(data.date||"")}}).catch(error=>{console.error(error);window.alert("This audit could not be loaded from the central database.")}).finally(()=>setHydrated(true))},[audit.id]);
  useEffect(()=>{if(!hydrated||!dirty||readOnly)return;const timer=window.setTimeout(()=>{fetch(`/api/audits/${audit.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({answers,residents,auditor,date,completed:false,score})}).then(response=>{if(!response.ok)throw new Error("Unable to save draft");onDraftSaved(audit.id);setDirty(false)}).catch(error=>console.error(error))},800);return()=>window.clearTimeout(timer)},[answers,residents,auditor,date,audit.id,hydrated,dirty,readOnly,score,onDraftSaved]);
  const setAnswer=(id:string,patch:Partial<Answer>)=>{if(readOnly)return;setDirty(true);setAnswers(prev=>({...prev,[id]:{...prev[id],...patch}}));};
  const addResident=()=>{if(!initials.trim()||!room.trim())return;setDirty(true);setResidents(prev=>[...prev,{id:crypto.randomUUID(),initials:initials.toUpperCase().slice(0,3),room}]);setInitials("");setRoom("")};
  const auditDate=date.replaceAll("-","");
  const reference=(r:Resident)=>`${r.initials}-${r.room.padStart(2,"0")}-${auditDate}`;
  const print=()=>window.print();
  const persist=async(completed:boolean)=>{const response=await fetch(`/api/audits/${audit.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({answers,residents,auditor,date,completed,score})});if(!response.ok)throw new Error("Database save failed")};
  const saveAudit=async()=>{const remaining=allQuestions.length-answered;try{await persist(false);onDraftSaved(audit.id);window.alert(audit.status==="completed"?"Changes have been saved to the central database.":`${remaining} ${remaining===1?"question is":"questions are"} unanswered. The audit has been saved centrally as in progress.`);onBack()}catch{window.alert("The audit could not be saved to the central database. Please try again.")}};
  const completeAudit=async()=>{const remaining=allQuestions.length-answered;if(remaining){window.alert(`${remaining} ${remaining===1?"question is":"questions are"} unanswered. Save the audit as in progress or answer every question before completing it.`);return;}try{await persist(true);onCompleted(audit.id,score);window.alert("Audit completed and saved to the central database.");onBack()}catch{window.alert("The audit could not be completed because the database save failed.")}};

  return <div className="audit-screen">
    <div className="audit-toolbar"><button className="back" onClick={onBack}>← All audits</button><div><button onClick={print}>Print</button><button onClick={print}>Create PDF</button>{readOnly&&<button className="primary-button" onClick={()=>window.alert("Return to the dashboard and choose Edit to make changes.")}>Read-only view</button>}</div></div>
    <div className="audit-layout">
      <aside className="audit-aside"><p className="eyebrow">{audit.department.toUpperCase()}</p><h1>{audit.name}</h1><div className="aside-meta"><span>CQC key question<strong>{audit.cqc}</strong></span><span>Frequency<strong>{audit.frequency}</strong></span></div><nav aria-label="Audit sections">{sections.map((s,i)=><a key={s.title} href={`#section-${i}`}><span>{i+1}</span>{s.title}<b>{s.questions.filter(q=>answers[q.id]?.rating).length}/{s.questions.length}</b></a>)}</nav><div className="audit-score"><Ring value={score} tone={score>=80?"green":score>=40?"amber":"red"}/><strong>Current audit score</strong><small>N/A answers are excluded</small></div></aside>
      <section className="audit-workspace">
        <div className="audit-heading"><div><p className="eyebrow">{readOnly?"COMPLETED AUDIT RECORD":"AUDIT WORKSPACE"}</p><h2>Representative resident sample</h2><p>Record every resident included in this audit using initials and room number only.</p></div><div className="completion"><strong>{answered}</strong><span>of {allQuestions.length}<br/>answered</span></div></div>
        <section className="sample-card">
          <div className="meta-fields"><label>Auditor<input disabled={readOnly} value={auditor} onChange={e=>{setDirty(true);setAuditor(e.target.value)}}/></label><label>Audit date<input disabled={readOnly} type="date" value={date} onChange={e=>{setDirty(true);setDate(e.target.value)}}/></label></div>
          <div className="sample-title"><div><h3>Sample residents <span>{residents.length}</span></h3><p>All references below form part of this audit record.</p></div>{!readOnly&&<div className="add-resident"><input aria-label="Resident initials" placeholder="Initials" value={initials} onChange={e=>setInitials(e.target.value)}/><input aria-label="Room number" placeholder="Room" value={room} onChange={e=>setRoom(e.target.value)}/><button onClick={addResident}>Add resident</button></div>}</div>
          <div className="resident-list">{residents.map(r=><div className="resident-chip" key={r.id}><span>{r.initials}</span><div><strong>{reference(r)}</strong><small>Room {r.room}</small></div>{!readOnly&&<button aria-label={`Remove ${reference(r)}`} onClick={()=>{setDirty(true);setResidents(prev=>prev.filter(x=>x.id!==r.id))}}>×</button>}</div>)}</div>
        </section>
        <section className="score-strip"><div><span>Current score</span><strong>{score}%</strong></div>{ratingOptions.slice(0,3).map(r=><div key={r.value}><span>{r.label}</span><strong>{Object.values(answers).filter(a=>a.rating===r.value).length}</strong><small>{r.points}% each</small></div>)}<div><span>N/A</span><strong>{Object.values(answers).filter(a=>a.rating==="na").length}</strong><small>Excluded</small></div></section>
        {sections.map((section,index)=><section className="question-section" id={`section-${index}`} key={section.title}><div className="section-heading"><span>{String(index+1).padStart(2,"0")}</span><div><p>SECTION {index+1} OF {sections.length}</p><h3>{section.title}</h3></div></div><div className="questions">{section.questions.map(q=>{const answer=answers[q.id]||{};const follow=answer.rating==="partial"||answer.rating==="not-met";return <article className="question" key={q.id}><div className="question-title"><span>{q.id}</span><div><h4>{q.text}</h4><p>{q.regulation}</p></div></div><fieldset disabled={readOnly}><legend className="sr-only">Outcome for {q.id}</legend>{ratingOptions.map(r=><label className={answer.rating===r.value?`checked ${r.value}`:""} key={r.value}><input type="radio" name={q.id} checked={answer.rating===r.value} onChange={()=>setAnswer(q.id,{rating:r.value})}/><i/>{r.label}<small>{r.value==="na"?"Excluded":`${r.points}%`}</small></label>)}</fieldset>{answer.rating&&<div className="follow-up"><label>Resident reference<select disabled={readOnly} value={answer.resident||"all"} onChange={e=>setAnswer(q.id,{resident:e.target.value})}><option value="all">All sampled residents</option>{residents.map(r=><option key={r.id} value={r.id}>{reference(r)}</option>)}</select></label><label>Evidence or comment {follow&&<b>Required</b>}<textarea disabled={readOnly} value={answer.comment||""} onChange={e=>setAnswer(q.id,{comment:e.target.value})} placeholder="Record the evidence reviewed and any finding..."/></label>{follow&&<label>Corrective action <b>Required</b><textarea disabled={readOnly} value={answer.action||""} onChange={e=>setAnswer(q.id,{action:e.target.value})} placeholder="State the action required, owner and timescale..."/></label>}</div>}</article>})}</div></section>)}
        {!readOnly&&<footer className="audit-footer"><div><strong>Save or complete this audit</strong><p>Partially completed audits are marked In progress without changing their due status.</p></div><div className="footer-actions"><button className="save-button" onClick={saveAudit}>Save audit</button><button className="primary-button" onClick={completeAudit}>Complete audit</button></div></footer>}
      </section>
    </div>
  </div>;
}
