// Brook Consultancy — Report Preview (3 documents)

function BrookHeader({ docTitle, docType, data, confidential }) {
  const f = data.fields || {};
  const date = f.consultation_date ? new Date(f.consultation_date).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' }) : '—';
  return (
    <div className="doc-header">
      <div className="doc-brand">
        <img src="assets/brook-mark.png" alt="" className="doc-brand-mark" />
        <div className="doc-brand-text">
          <div className="doc-brand-name">Brook Consultancy</div>
          <div className="doc-brand-sub">Partners Ltd</div>
        </div>
      </div>
      <div className="doc-title-block">
        <div className="eyebrow">{docType}</div>
        <h1>{docTitle}</h1>
        {f.org_name && <div className="doc-prepared-for">Prepared for {f.org_name}</div>}
      </div>
      <div className="doc-meta">
        <div><strong>Consultation date</strong> {date}</div>
        <div><strong>Consultant</strong> {f.consultant_name || '—'}</div>
        {f.client_contact_name && <div><strong>Client contact</strong> {f.client_contact_name}</div>}
        {confidential && <div className="doc-confidential">● Confidential — Internal</div>}
      </div>
    </div>
  );
}

function BrookFooter({ docId, page }) {
  return (
    <div className="footer-strip">
      <div className="footer-brand">
        <img src="assets/brook-mark.png" alt="" className="footer-mark" />
        <span><strong>Brook Consultancy Partners Ltd</strong> · Strictly confidential</span>
      </div>
      <span>{docId}{page ? ` · ${page}` : ''}</span>
    </div>
  );
}

// Defensive helper — always returns an array regardless of input shape
function asArray(v) {
  if (Array.isArray(v)) return v;
  if (v === undefined || v === null || v === '') return [];
  if (typeof v === 'string') return v.split(/[,\n]/).map(s => s.trim()).filter(Boolean);
  return [];
}

function joinList(arr) { return asArray(arr).filter(Boolean).join(', '); }

// Render textarea content as one or more paragraphs, preserving line breaks,
// and ensuring each paragraph ends with terminal punctuation.
function Prose({ text, className, style }) {
  if (!text) return null;
  const paragraphs = String(text)
    .split(/\n{2,}/)
    .map(p => p.trim())
    .filter(Boolean);
  if (paragraphs.length === 0) return null;
  return (
    <>
      {paragraphs.map((p, i) => (
        <p key={i} className={className} style={{ whiteSpace: 'pre-wrap', ...(style || {}) }}>
          {ensureTerminalPunctuation(p)}
        </p>
      ))}
    </>
  );
}

// Append a full stop if there's no terminal punctuation already.
function ensureTerminalPunctuation(text) {
  if (!text) return text;
  const trimmed = String(text).trimEnd();
  if (!trimmed) return trimmed;
  if (/[.!?…:;)"'\]]$/.test(trimmed)) return trimmed;
  return trimmed + '.';
}

// Inline (non-paragraph) — strip wrapping whitespace and ensure terminal punctuation.
function inlineText(text) {
  return ensureTerminalPunctuation(String(text || '').trim());
}

function tryDate(v) {
  if (!v) return '—';
  try { return new Date(v).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' }); }
  catch { return v; }
}

// Adapter — maps the canonical `aiResults` tree (mirrors the Ofsted EYFS app shape)
// back to the legacy `dash` shape that the report components expect.
function aiResultsToDash(data) {
  const ai = data.aiResults || {};
  const areas = {};
  Object.keys(ai).forEach(k => {
    if (k !== 'statutory' && k !== 'findings' && k !== 'executive_summary' && k !== 'autofill') areas[k] = ai[k];
  });
  const exec = ai.executive_summary || {};
  return {
    areas,
    compliance: asArray(ai.statutory?.findings),
    strengths: asArray(ai.findings?.strengths),
    areas_for_development: asArray(ai.findings?.afd),
    actions: asArray(ai.findings?.actions),
    executive_summary: {
      overall_assessment: exec.overall_assessment || '',
      key_risks: asArray(exec.key_risks),
      immediate_priorities: asArray(exec.immediate_priorities)
    }
  };
}

// Returns repeaters with all keys guaranteed to be arrays
function safeRepeaters(data) {
  const r = data.repeaters || {};
  return {
    quotes: asArray(r.quotes),
    evidence: asArray(r.evidence),
    workstreams: asArray(r.workstreams)
  };
}

// ---------------------------------------------------------------
// DOCUMENT 1 — INTERNAL BRIEFING NOTE
// ---------------------------------------------------------------
function InternalBriefing({ data }) {
  const f = data.fields || {};
  const dash = aiResultsToDash(data);
  const reps = safeRepeaters(data);
  return (
    <div className="report-page">
      <BrookHeader docTitle="Internal Consultation Briefing" docType="Document 1 · Internal" data={data} confidential />

      <div className="report-confidential">⚠ Internal use only — not for circulation outside Brook Consultancy</div>

      <h2>1. Consultation Overview</h2>
      <table className="data-table">
        <tbody>
          <tr><th>Organisation</th><td>{f.org_name || '—'}</td></tr>
          <tr><th>Type</th><td>{f.org_type || '—'}</td></tr>
          <tr><th>Region</th><td>{f.la_region || '—'}</td></tr>
          <tr><th>Client contact</th><td>{f.client_contact_name || '—'} {f.client_contact_email && `(${f.client_contact_email})`}</td></tr>
          <tr><th>Consultation method</th><td>{f.consultation_method || '—'}</td></tr>
          <tr><th>Consultant</th><td>{f.consultant_name || '—'}</td></tr>
          <tr><th>Date</th><td>{tryDate(f.consultation_date)}</td></tr>
          <tr><th>Auto-complete used</th><td>{data._autofill_used ? 'Yes' : 'No'}</td></tr>
        </tbody>
      </table>

      <h2>2. Lead Assessment</h2>
      <table className="data-table">
        <tbody>
          <tr><th>Lead priority</th><td>{f.lead_priority || '—'}</td></tr>
          <tr><th>Brook risk level</th><td>{f.brook_risk_level || '—'}</td></tr>
          <tr><th>Engagement scope</th><td>{f.engagement_scope || '—'}</td></tr>
          <tr><th>Self-awareness</th><td>{f.self_awareness || '—'}</td></tr>
          <tr><th>Engagement level</th><td>{f.engagement_level || '—'}</td></tr>
          <tr><th>Indicative investment</th><td>{f.investment_range || f.budget_for_support || '—'}</td></tr>
          <tr><th>Timeline to start</th><td>{f.timeline_to_start || '—'}</td></tr>
          <tr><th>Proposal deadline</th><td>{tryDate(f.proposal_deadline)}</td></tr>
        </tbody>
      </table>

      <h2>3. Consultant Assessment</h2>
      <h3>Overall impression</h3>
      {f.overall_impression ? <Prose text={f.overall_impression} /> : <p>—</p>}
      <h3>Leadership credibility</h3>
      {f.leadership_credibility ? <Prose text={f.leadership_credibility} /> : <p>—</p>}
      <h3>Key risks identified</h3>
      {f.key_risks ? <Prose text={f.key_risks} /> : <p>—</p>}
      <h3>Red flags observed</h3>
      {f.red_flags ? <Prose text={f.red_flags} /> : <p>—</p>}
      {f.escalation_required === 'Yes' && (
        <>
          <h3 style={{ color: '#c0392b' }}>⚠ Escalation required</h3>
          {f.escalation_notes ? <Prose text={f.escalation_notes} /> : <p>—</p>}
        </>
      )}

      <h2>4. Recommended Services</h2>
      <p>{joinList(f.recommended_services) ? joinList(f.recommended_services) + '.' : '—'}</p>

      <h2>5. Next Steps</h2>
      <h3>Immediate next steps</h3>
      {f.recommended_next_steps ? <Prose text={f.recommended_next_steps} /> : <p>—</p>}
      <h3>Brook actions before proposal</h3>
      {f.brook_actions ? <Prose text={f.brook_actions} /> : <p>—</p>}
      <h3>Client actions requested</h3>
      {f.client_actions ? <Prose text={f.client_actions} /> : <p>—</p>}

      <h2>6. Full Consultation Notes</h2>
      <h3>Organisation overview</h3>
      {(f.history_notes || f.size_notes || f.leadership_notes)
        ? <Prose text={f.history_notes || f.size_notes || f.leadership_notes} />
        : <p>—</p>}
      <h3>What the client is asking for</h3>
      {f.client_request ? <Prose text={f.client_request} /> : <p>—</p>}
      <h3>Stated priorities</h3>
      {f.stated_priorities ? <Prose text={f.stated_priorities} /> : <p>—</p>}
      <h3>Consultant reflection (gap assessment)</h3>
      <p><strong>{f.gap_assessment || '—'}</strong></p>
      <Prose text={f.consultant_reflection} />
      <h3>Trigger</h3>
      {f.trigger_notes ? <Prose text={f.trigger_notes} /> : <p>—</p>}
      {f.urgency && <p style={{ marginTop: -4 }}><span style={{ fontFamily: 'var(--font-sans)', fontSize: 11, padding: '2px 8px', borderRadius: 8, background: '#fef3c7', color: '#854d0e' }}>Urgency: {f.urgency}</span></p>}
      <h3>Core challenges</h3>
      {f.core_challenges ? <Prose text={f.core_challenges} /> : <p>—</p>}
      <p style={{ fontSize: 11, color: '#5a6477' }}>Tags: {joinList(f.challenge_tags) || '—'}</p>
      <h3>Impact</h3>
      {f.impact_notes ? <Prose text={f.impact_notes} /> : <p>—</p>}
      <h3>Previous attempts</h3>
      {f.previous_attempts ? <Prose text={f.previous_attempts} /> : <p>—</p>}

      <h3>Compliance & regulatory position</h3>
      {f.regulatory_notes ? <Prose text={f.regulatory_notes} /> : <p>—</p>}
      <p style={{ fontSize: 11, color: '#5a6477' }}>
        Regulators: {joinList(f.regulatory_bodies) || '—'} · Status: {f.regulatory_status || '—'}
      </p>
      <h3>Safeguarding</h3>
      {f.safeguarding_notes ? <Prose text={f.safeguarding_notes} /> : <p>—</p>}
      <h3>Policies & documentation</h3>
      {f.policy_notes ? <Prose text={f.policy_notes} /> : <p>—</p>}
      <p style={{ fontSize: 11, color: '#5a6477' }}>Status: {f.policy_status || 'TBD'}</p>

      <h3>Systems & operations</h3>
      <p><strong>Finance: </strong>{inlineText(f.finance_systems_notes) || '—'} {asArray(f.finance_systems).length > 0 && <em>({joinList(f.finance_systems)})</em>}</p>
      <p><strong>HR: </strong>{inlineText(f.hr_systems_notes) || '—'} {asArray(f.hr_systems).length > 0 && <em>({joinList(f.hr_systems)})</em>}</p>
      <p><strong>Operational: </strong>{inlineText(f.operational_systems) || '—'}</p>
      <p><strong>Data maturity: </strong>{f.data_maturity || '—'}{f.data_notes ? ` — ${inlineText(f.data_notes)}` : ''}</p>

      <h3>Financial picture</h3>
      {f.financial_overview ? <Prose text={f.financial_overview} /> : <p>—</p>}
      <p style={{ fontSize: 11, color: '#5a6477' }}>Budget band: {f.budget_range || '—'} · Position: {f.financial_position || '—'} · Income types: {joinList(f.income_sources) || '—'}</p>
      <h3>People & culture</h3>
      {f.workforce_notes ? <Prose text={f.workforce_notes} /> : <p>—</p>}
      <Prose text={f.retention_notes} />
      <Prose text={f.performance_notes} />
      <h3>Strategic goals</h3>
      <p><strong>Short-term: </strong>{inlineText(f.short_term_priorities) || '—'}</p>
      <p><strong>Long-term: </strong>{inlineText(f.long_term_vision) || '—'}</p>
      <p><strong>Partnership expectations: </strong>{inlineText(f.partnership_expectations) || '—'}</p>

      {/* Section 10 evidence */}
      <h2>7. Section 10 — Evidence Captured</h2>
      <h3>Key client quotes</h3>
      {reps.quotes.length === 0 && <p style={{ color: '#8a93a4', fontStyle: 'italic' }}>None captured.</p>}
      {reps.quotes.map((q, i) => (
        <div className="quote-block" key={q.id || i}>
          {q.quote || '—'}
          <span className="quote-attr">— {q.context || 'context not captured'} {q.tag && `· tag: ${q.tag}`}</span>
        </div>
      ))}

      <h3>Specific evidence & facts</h3>
      {reps.evidence.length === 0 && <p style={{ color: '#8a93a4', fontStyle: 'italic' }}>None captured.</p>}
      {reps.evidence.length > 0 && (
        <table className="data-table">
          <thead><tr><th>Evidence</th><th style={{ width: 110 }}>Category</th><th style={{ width: 140 }}>Source</th></tr></thead>
          <tbody>
            {reps.evidence.map((e, i) => <tr key={e.id || i}><td>{e.text}</td><td>{e.category || '—'}</td><td>{e.source || '—'}</td></tr>)}
          </tbody>
        </table>
      )}

      <h3>Baseline metrics</h3>
      <table className="data-table">
        <tbody>
          <tr><th>Annual budget / turnover</th><td>{f.annual_budget || f.budget_range || '—'}</td></tr>
          <tr><th>Financial position detail</th><td>{f.financial_position_detail || f.financial_position || '—'}</td></tr>
          <tr><th>Staff count</th><td>{f.staff_count_detail || f.staff_count || '—'}</td></tr>
          <tr><th>Vacancies</th><td>{f.staff_vacancy_detail || '—'}</td></tr>
          <tr><th>Turnover rate</th><td>{f.staff_turnover || '—'}</td></tr>
          <tr><th>Service users</th><td>{f.service_users_detail || f.service_users || '—'}</td></tr>
          <tr><th>Regulatory rating</th><td>{f.regulatory_rating || '—'}</td></tr>
          <tr><th>Last inspection</th><td>{tryDate(f.last_inspection_date)}</td></tr>
          <tr><th>KPIs tracked</th><td>{f.kpis_tracked || '—'}</td></tr>
          <tr><th>Other figures</th><td>{f.other_metrics || '—'}</td></tr>
        </tbody>
      </table>

      {/* Dashboard if used */}
      {data._autofill_used && dash.executive_summary && dash.executive_summary.overall_assessment && (
        <>
          <h2>8. Assessment Dashboard Output</h2>
          <h3>Executive assessment</h3>
          <p>{dash.executive_summary.overall_assessment}</p>
          {dash.executive_summary.key_risks?.length > 0 && (
            <>
              <h3>Key risks</h3>
              <ul>{dash.executive_summary.key_risks.map((r, i) => <li key={i}>{r}</li>)}</ul>
            </>
          )}
          {dash.executive_summary.immediate_priorities?.length > 0 && (
            <>
              <h3>Immediate priorities</h3>
              <ul>{dash.executive_summary.immediate_priorities.map((r, i) => <li key={i}>{r}</li>)}</ul>
            </>
          )}

          {Object.keys(dash.areas || {}).length > 0 && (
            <>
              <h3>Evaluation area summary</h3>
              <table className="data-table">
                <thead><tr><th>Area</th><th style={{ width: 140 }}>Grade</th><th>Reasoning</th></tr></thead>
                <tbody>
                  {window.BROOK_SCHEMA.evaluationAreas.map(a => {
                    const ad = dash.areas[a.id];
                    if (!ad) return null;
                    const gs = window.getGradeStyle(ad.suggestedGrade);
                    return <tr key={a.id}><td><strong>{a.name}</strong></td><td><span style={{ color: gs.color, background: gs.background, padding: '2px 8px', borderRadius: 8, fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em' }}>{gs.label}</span></td><td>{ad.gradeReasoning || '—'}</td></tr>;
                  })}
                </tbody>
              </table>
            </>
          )}

          {dash.actions?.length > 0 && (
            <>
              <h3>Action plan</h3>
              <table className="data-table">
                <thead><tr><th>Action</th><th>Owner</th><th>Priority</th><th>Timeline</th></tr></thead>
                <tbody>
                  {dash.actions.map((a, i) => <tr key={i}><td>{a.action}</td><td>{a.owner || '—'}</td><td>{a.priority || '—'}</td><td>{a.timeline || '—'}</td></tr>)}
                </tbody>
              </table>
            </>
          )}
        </>
      )}

      <BrookFooter docId="DOC-1 · Internal Briefing" />
    </div>
  );
}

// ---------------------------------------------------------------
// DOCUMENT 2 — CLIENT FOLLOW-UP SUMMARY
// ---------------------------------------------------------------
function ClientSummary({ data }) {
  const f = data.fields || {};
  const reps = safeRepeaters(data);
  const quotes = reps.quotes.slice(0, 3);
  const workstreams = reps.workstreams;
  const recommendedServices = asArray(f.recommended_services);
  const challengeTags = asArray(f.challenge_tags);
  return (
    <div className="report-page">
      <BrookHeader docTitle="Thank you for our conversation" docType="Document 2 · Client Follow-Up" data={data} />

      <p style={{ fontSize: 14 }}>Dear {f.client_contact_name?.split(' ')[0] || 'colleague'},</p>

      <p>Thank you for taking the time to speak with me about <strong>{f.org_name || 'your organisation'}</strong>. It was a pleasure to hear about the work you do{f.la_region ? ` in ${f.la_region}` : ''} and to begin understanding the situation you are working through. This note is a short summary of what we discussed, captured while it is fresh, alongside our suggested next steps.</p>

      <h2>What we discussed</h2>
      <Prose text={f.history_notes} />
      {f.client_request && (
        <>
          <h3>What you are looking for</h3>
          <Prose text={f.client_request} />
        </>
      )}
      {f.stated_priorities && (
        <>
          <h3>Your stated priorities</h3>
          <Prose text={f.stated_priorities} />
        </>
      )}

      {(f.core_challenges || challengeTags.length > 0) && (
        <>
          <h2>Challenges we acknowledged</h2>
          <Prose text={f.core_challenges} />
          {challengeTags.length > 0 && (
            <p style={{ fontSize: 12, color: '#5a6477' }}><em>Themes:</em> {joinList(challengeTags)}.</p>
          )}
        </>
      )}

      {quotes.length > 0 && (
        <>
          <h2>What stood out</h2>
          <p>A few of the things you said that we will be carrying forward into our thinking:</p>
          {quotes.map((q, i) => (
            <div className="quote-block" key={q.id || i}>
              {q.quote}
              {q.tag && <span className="quote-attr">— on {q.tag.toLowerCase()}</span>}
            </div>
          ))}
        </>
      )}

      <h2>How we think we can help</h2>
      {recommendedServices.length > 0 && (
        <>
          <p>Based on our conversation, the areas of Brook's support most relevant to you are:</p>
          <ul>{recommendedServices.map((s, i) => <li key={i}>{s}</li>)}</ul>
        </>
      )}
      {workstreams.length > 0 && (
        <>
          <h3>Suggested workstreams</h3>
          <ul>{workstreams.map((w, i) => <li key={w.id || i}><strong>{w.title || 'Workstream'}</strong>{w.description ? ` — ${w.description}` : ''}{w.timeframe ? ` (${w.timeframe})` : ''}</li>)}</ul>
        </>
      )}

      <h2>Agreed next steps</h2>
      <Prose text={f.recommended_next_steps} />
      {f.client_actions && (
        <>
          <h3>From your side</h3>
          <Prose text={f.client_actions} />
        </>
      )}
      {f.brook_actions && (
        <>
          <h3>From our side</h3>
          <Prose text={f.brook_actions} />
        </>
      )}
      {f.proposal_deadline && <p>We will come back to you with a written proposal by <strong>{tryDate(f.proposal_deadline)}</strong>.</p>}

      <p style={{ marginTop: 30 }}>
        Thank you again for your candour and your time. We know how rare it is to be able to speak openly about what is genuinely difficult inside an organisation, and we appreciated the trust you placed in this conversation.
      </p>
      <p>
        With kind regards,<br/>
        <strong>{f.consultant_name || 'The Brook Consultancy team'}</strong><br/>
        Brook Consultancy Partners
      </p>

      <BrookFooter docId="DOC-2 · Client Follow-Up" />
    </div>
  );
}

// ---------------------------------------------------------------
// DOCUMENT 3 — REPORT FIRST DRAFT SHELL
// ---------------------------------------------------------------
function ReportDraft({ data }) {
  const f = data.fields;
  const dash = aiResultsToDash(data);
  const DEFAULT_SECTIONS = ['Executive Summary','About Brook Consultancy (standard boilerplate)','Background & Context','Organisation Overview','Key Challenges Identified','Compliance & Regulatory Position','Financial Position Summary','Systems & Operations Review','People & Culture Assessment','Client Goals & Strategic Ambitions','Our Assessment & Recommendations','Proposed Scope of Work','Indicative Investment & Timeline','Why Brook Consultancy','Next Steps'];
  // Be tolerant: report_sections may be array, comma-separated string, or missing
  let sections = f.report_sections;
  if (!Array.isArray(sections)) {
    if (typeof sections === 'string' && sections.trim()) {
      sections = sections.split(/[,\n]/).map(s => s.trim()).filter(Boolean);
    } else {
      sections = DEFAULT_SECTIONS;
    }
  }
  if (sections.length === 0) sections = DEFAULT_SECTIONS;
  const incl = (id) => sections.some(s => typeof s === 'string' && s.toLowerCase().startsWith(id.toLowerCase()));

  const narrative = [f.narrative_p1, f.narrative_p2, f.narrative_p3, f.narrative_p4].filter(Boolean);
  const reps = safeRepeaters(data);
  const inlineQuotes = (tag) => reps.quotes.filter(q => (q.tag || '').toLowerCase() === tag.toLowerCase());

  return (
    <div className="report-page">
      <BrookHeader docTitle={`Operational Review & Recommendations`} docType="Document 3 · Report First Draft" data={data} />

      {f.report_angle && (
        <div style={{ background: '#fbf3df', border: '1px solid #e8d8a8', padding: '10px 14px', borderRadius: 6, fontSize: 11.5, fontFamily: 'var(--font-sans)', color: '#6e5314', margin: '0 0 16px' }}>
          <strong>Editor's note:</strong> {f.report_angle}
        </div>
      )}

      {incl('Executive') && (
        <>
          <h2>1. Executive Summary</h2>
          {dash.executive_summary?.overall_assessment && <Prose text={dash.executive_summary.overall_assessment} />}
          {!dash.executive_summary?.overall_assessment && narrative[0] && <Prose text={narrative[0]} />}
          {dash.executive_summary?.key_risks?.length > 0 && (
            <>
              <h3>Headline risks</h3>
              <ul>{dash.executive_summary.key_risks.map((r, i) => <li key={i}>{r}</li>)}</ul>
            </>
          )}
        </>
      )}

      {incl('About Brook') && (
        <>
          <h2>2. About Brook Consultancy</h2>
          <p>Brook Consultancy Partners is a UK-based business management consultancy specialising in operational, regulatory and financial recovery for organisations operating in regulated and high-stakes environments. We work primarily with care providers, nonprofits, faith-based organisations and small-to-mid-market enterprises, providing both strategic advisory and hands-on delivery support.</p>
          <p>Our approach is grounded in evidence, anchored in operational reality, and delivered with discretion. Engagements are scoped tightly, reported on transparently, and structured around outcomes the client can verify.</p>
        </>
      )}

      {incl('Background') && narrative.length > 0 && (
        <>
          <h2>3. Background & Context</h2>
          {narrative.map((p, i) => <p key={i} style={{ whiteSpace: 'pre-wrap' }}>{ensureTerminalPunctuation(p)}</p>)}
        </>
      )}

      {incl('Organisation Overview') && (
        <>
          <h2>4. Organisation Overview</h2>
          <table className="data-table">
            <tbody>
              <tr><th style={{ width: 220 }}>Organisation</th><td>{f.org_name || '—'}</td></tr>
              <tr><th>Type</th><td>{f.org_type || '—'}</td></tr>
              <tr><th>Region</th><td>{f.la_region || '—'}</td></tr>
              <tr><th>Staff</th><td>{f.staff_count_detail || f.staff_count || '—'}</td></tr>
              <tr><th>Service users / clients</th><td>{f.service_users_detail || f.service_users || '—'}</td></tr>
              <tr><th>Sites</th><td>{f.sites || '—'}</td></tr>
              <tr><th>Regulatory rating</th><td>{f.regulatory_rating || f.regulatory_status || '—'}</td></tr>
              <tr><th>Annual budget / turnover</th><td>{f.annual_budget || f.budget_range || '—'}</td></tr>
            </tbody>
          </table>
          <Prose text={f.history_notes} />
          {f.leadership_notes && (
            <>
              <h3>Leadership & structure</h3>
              <Prose text={f.leadership_notes} />
              {inlineQuotes('Leadership').slice(0, 1).map((q, i) => (
                <div className="quote-block" key={q.id || i}>{q.quote}<span className="quote-attr">— {q.context || 'leadership'}</span></div>
              ))}
            </>
          )}
        </>
      )}

      {incl('Key Challenges') && (
        <>
          <h2>5. Key Challenges Identified</h2>
          <Prose text={f.core_challenges} />
          {f.impact_notes && <p><strong>Impact: </strong>{inlineText(f.impact_notes)}</p>}
          {asArray(f.challenge_tags).length > 0 && (
            <p style={{ fontFamily: 'var(--font-sans)', fontSize: 12, color: '#5a6477' }}>Thematic tags: {joinList(f.challenge_tags)}.</p>
          )}
          {dash.areas_for_development.length > 0 && (
            <>
              <h3>Areas requiring development</h3>
              <ul>{dash.areas_for_development.map((a, i) => <li key={i}>{a}</li>)}</ul>
            </>
          )}
        </>
      )}

      {incl('Compliance') && (
        <>
          <h2>6. Compliance & Regulatory Position</h2>
          <Prose text={f.regulatory_notes} />
          {f.regulatory_status && (
            <p><strong>Current standing: </strong>{f.regulatory_status}{asArray(f.regulatory_bodies).length > 0 && <span> ({joinList(f.regulatory_bodies)})</span>}.</p>
          )}
          {f.safeguarding_notes && (
            <>
              <h3>Safeguarding</h3>
              <Prose text={f.safeguarding_notes} />
            </>
          )}
          {f.policy_notes && (
            <>
              <h3>Policies & documentation</h3>
              <Prose text={f.policy_notes} />
              <p style={{ fontSize: 12, color: '#5a6477', marginTop: -4 }}><em>Status: {f.policy_status || 'to confirm'}.</em></p>
            </>
          )}
        </>
      )}

      {incl('Financial') && (
        <>
          <h2>7. Financial Position Summary</h2>
          <Prose text={f.financial_overview} />
          <table className="data-table">
            <tbody>
              <tr><th style={{ width: 220 }}>Annual turnover / budget</th><td>{f.annual_budget || f.budget_range || '—'}</td></tr>
              <tr><th>Financial position</th><td>{f.financial_position_detail || f.financial_position || '—'}</td></tr>
              <tr><th>Income types</th><td>{joinList(f.income_sources) || '—'}</td></tr>
            </tbody>
          </table>
          {f.cost_pressures && (
            <>
              <h3>Cost base & pressures</h3>
              <Prose text={f.cost_pressures} />
            </>
          )}
          {f.financial_controls_notes && (
            <>
              <h3>Financial controls</h3>
              <Prose text={f.financial_controls_notes} />
            </>
          )}
        </>
      )}

      {incl('Systems') && (f.finance_systems_notes || f.hr_systems_notes || f.operational_systems || f.data_notes) && (
        <>
          <h2>8. Systems & Operations Review</h2>
          {f.finance_systems_notes && <p><strong>Finance: </strong>{inlineText(f.finance_systems_notes)}</p>}
          {f.hr_systems_notes && <p><strong>HR: </strong>{inlineText(f.hr_systems_notes)}</p>}
          {f.operational_systems && <p><strong>Operations: </strong>{inlineText(f.operational_systems)}</p>}
          {f.data_notes && <p><strong>Data & reporting ({f.data_maturity || 'maturity TBC'}): </strong>{inlineText(f.data_notes)}</p>}
        </>
      )}

      {incl('People') && (
        <>
          <h2>9. People & Culture Assessment</h2>
          <Prose text={f.workforce_notes} />
          <Prose text={f.retention_notes} />
          <Prose text={f.performance_notes} />
          {inlineQuotes('People').slice(0, 1).map((q, i) => (
            <div className="quote-block" key={q.id || i}>{q.quote}<span className="quote-attr">— {q.context || 'on people'}</span></div>
          ))}
        </>
      )}

      {incl('Client Goals') && (
        <>
          <h2>10. Client Goals & Strategic Ambitions</h2>
          {f.short_term_priorities && <p><strong>Short-term: </strong>{inlineText(f.short_term_priorities)}</p>}
          {f.long_term_vision && <p><strong>Long-term vision: </strong>{inlineText(f.long_term_vision)}</p>}
          {f.partnership_expectations && <p><strong>Partnership expectations: </strong>{inlineText(f.partnership_expectations)}</p>}
        </>
      )}

      {incl('Our Assessment') && (
        <>
          <h2>11. Our Assessment & Recommendations</h2>
          {dash.executive_summary?.overall_assessment && <Prose text={dash.executive_summary.overall_assessment} />}
          {!dash.executive_summary?.overall_assessment && narrative[3] && <Prose text={narrative[3]} />}
          {dash.strengths && dash.strengths.length > 0 && (
            <>
              <h3>Strengths to build on</h3>
              <ul>{dash.strengths.map((s, i) => <li key={i}>{s}</li>)}</ul>
            </>
          )}
          {dash.actions && dash.actions.length > 0 && (
            <>
              <h3>Recommended action plan</h3>
              <table className="data-table">
                <thead><tr><th>Action</th><th style={{ width: 140 }}>Owner</th><th style={{ width: 100 }}>Priority</th><th style={{ width: 140 }}>Timeline</th></tr></thead>
                <tbody>
                  {dash.actions.map((a, i) => <tr key={i}><td>{a.action}</td><td>{a.owner || '—'}</td><td>{a.priority || '—'}</td><td>{a.timeline || '—'}</td></tr>)}
                </tbody>
              </table>
            </>
          )}
        </>
      )}

      {incl('Proposed Scope') && reps.workstreams.length > 0 && (
        <>
          <h2>12. Proposed Scope of Work</h2>
          <table className="data-table">
            <thead><tr><th>Workstream</th><th>Description</th><th style={{ width: 110 }}>Timeframe</th><th style={{ width: 100 }}>Priority</th></tr></thead>
            <tbody>
              {reps.workstreams.map((w, i) => (
                <tr key={w.id || i}>
                  <td><strong>{w.title || '—'}</strong></td>
                  <td>{w.description || '—'}</td>
                  <td>{w.timeframe || '—'}</td>
                  <td>{w.priority || '—'}</td>
                </tr>
              ))}
            </tbody>
          </table>
          {f.dependencies && <p><strong>Key dependencies: </strong>{inlineText(f.dependencies)}</p>}
          {f.success_definition && <p><strong>Success at the end of this engagement looks like: </strong>{inlineText(f.success_definition)}</p>}
        </>
      )}

      {incl('Indicative Investment') && (
        <>
          <h2>13. Indicative Investment & Timeline</h2>
          <table className="data-table">
            <tbody>
              <tr><th style={{ width: 220 }}>Engagement length</th><td>{f.engagement_length || '—'}</td></tr>
              <tr><th>Indicative investment</th><td>{f.investment_range || f.budget_for_support || '—'}</td></tr>
              <tr><th>Earliest start</th><td>{f.timeline_to_start || '—'}</td></tr>
            </tbody>
          </table>
          <p style={{ fontStyle: 'italic', color: '#5a6477', fontSize: 12 }}>Final investment, scope, and milestones will be confirmed in our written proposal following internal review.</p>
        </>
      )}

      {incl('Why Brook') && (
        <>
          <h2>14. Why Brook Consultancy</h2>
          <p>Brook combines hands-on operational depth with the discipline of a regulated-industry advisory practice. We work alongside leadership teams in moments where the cost of getting things wrong is high and where evidence, discretion and pace matter equally.</p>
          <ul>
            <li>Regulated-sector experience across CQC, charity, and commercial environments</li>
            <li>Senior consultants with operating-line backgrounds — not career advisors</li>
            <li>Clear, evidence-anchored deliverables and milestones</li>
            <li>Confidentiality protocols designed for sensitive engagements</li>
          </ul>
        </>
      )}

      {incl('Next Steps') && (
        <>
          <h2>15. Next Steps</h2>
          <Prose text={f.recommended_next_steps} />
          {f.proposal_deadline && <p>A written proposal will be issued by <strong>{tryDate(f.proposal_deadline)}</strong>.</p>}
        </>
      )}

      <BrookFooter docId="DOC-3 · Report Draft" />
    </div>
  );
}

// ---------------------------------------------------------------
// Error boundary — so a bad field can't take down the whole report screen
// ---------------------------------------------------------------
class ReportErrorBoundary extends React.Component {
  constructor(props) { super(props); this.state = { error: null }; }
  static getDerivedStateFromError(error) { return { error }; }
  componentDidCatch(error, info) { console.error('Report render error:', error, info); }
  render() {
    if (this.state.error) {
      return (
        <div className="report-page">
          <h2 style={{ color: '#c0392b' }}>Could not render this document</h2>
          <p>One of the fields contains data in an unexpected shape — most often this happens after importing an older consultation file.</p>
          <pre style={{ background: '#f7f8fa', padding: 12, borderRadius: 6, fontSize: 11, overflow: 'auto' }}>{String(this.state.error?.message || this.state.error)}</pre>
          <p style={{ fontSize: 13, color: '#5a6477', marginTop: 16 }}>
            Try switching to a different document tab, or open the consultation form, save the affected field, and re-generate the report.
          </p>
          <button className="btn btn-primary" style={{ marginTop: 12 }} onClick={() => this.setState({ error: null })}>Try again</button>
        </div>
      );
    }
    return this.props.children;
  }
}

// ---------------------------------------------------------------
// REPORT VIEW WRAPPER
// ---------------------------------------------------------------
function ReportView({ data, onBack, onMarkComplete }) {
  const [tab, setTab] = React.useState('draft');

  const emailClient = () => {
    const f = (data && data.fields) || {};
    const to = (f.client_contact_email || '').trim();
    if (!to) {
      alert("No client email captured on this record. Add it in Section 1.1 (Basic Details) and try again.");
      return;
    }
    const firstName = (f.client_contact_name || '').split(/\s+/)[0] || 'colleague';
    const orgName = f.org_name || 'your organisation';
    const subject = `Your strategic review from Brook Consultancy`;
    const body =
`Dear ${firstName},

It was a pleasure speaking with you today about ${orgName}.

Please find your tailored one-pager attached as a PDF. It captures the headline themes from our 30-minute conversation, the areas we'd recommend focusing on next, and some practical first steps you can take this week.

We'll be in touch shortly with a follow-up.

With kind regards,
${f.consultant_name || 'The Brook Consultancy team'}
Brook Consultancy Partners Ltd

— —
Note for the team member sending this: mailto: links can't attach files. Open the Report view, switch to the Client Summary tab, choose 'Print → Save as PDF', then drag-and-drop the resulting PDF onto this email before sending. The internal briefing should be sent separately to info@brookconsultancy.co.uk.`;
    const href = `mailto:${encodeURIComponent(to)}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
    window.location.href = href;
  };

  const markCompleteAndEmail = () => {
    if (onMarkComplete) onMarkComplete();
    emailClient();
  };

  return (
    <div>
      <div className="report-toolbar">
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <button className="btn" onClick={onBack}>← Back to consultation</button>
          <div className="report-tabs">
            <button className={`report-tab${tab === 'internal' ? ' active' : ''}`} onClick={() => setTab('internal')}>Doc 1 · Internal Briefing</button>
            <button className={`report-tab${tab === 'client' ? ' active' : ''}`} onClick={() => setTab('client')}>Doc 2 · Client Summary</button>
            <button className={`report-tab${tab === 'draft' ? ' active' : ''}`} onClick={() => setTab('draft')}>Doc 3 · Report Draft</button>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn" onClick={() => window.print()}>🖨 Print / Save as PDF</button>
          <button className="btn" onClick={emailClient} title="Open your mail client with a pre-filled email to the prospect">✉ Email client</button>
          {onMarkComplete && (
            <button className="btn btn-amber" onClick={markCompleteAndEmail}>
              ✓ Mark complete &amp; email client
            </button>
          )}
        </div>
      </div>
      <div style={{ background: '#e8ecf1', minHeight: '100vh', paddingBottom: 40 }}>
        <ReportErrorBoundary key={tab}>
          {tab === 'internal' && <InternalBriefing data={data} />}
          {tab === 'client' && <ClientSummary data={data} />}
          {tab === 'draft' && <ReportDraft data={data} />}
        </ReportErrorBoundary>
      </div>
    </div>
  );
}

Object.assign(window, { ReportView, InternalBriefing, ClientSummary, ReportDraft });
