// Brook Consultancy — section renderer + dashboard

function ProbesPanel({ probes }) {
  const [open, setOpen] = React.useState(false);
  if (!probes || !probes.length) return null;
  return (
    <div className="probes">
      <button className={`probes-toggle${open ? ' open' : ''}`} onClick={() => setOpen(!open)}>
        <span><span style={{ marginRight: 6 }}>💬</span>{open ? 'Hide' : 'Show'} {probes.length} follow-up probe{probes.length !== 1 ? 's' : ''}</span>
        <span className="chev">▶</span>
      </button>
      {open && (
        <ol className="probes-list">
          {probes.map((p, i) => <li key={i}>{p}</li>)}
        </ol>
      )}
    </div>
  );
}

function SubsectionCard({ section, sub, store }) {
  const fieldComponents = (sub.fields || []).map(field => {
    if (field.type === 'repeater_quotes') {
      return <window.QuoteRepeater key={field.id} items={store.data.repeaters.quotes} onChange={(v) => store.setRepeater('quotes', v)} />;
    }
    if (field.type === 'repeater_evidence') {
      return <window.EvidenceRepeater key={field.id} items={store.data.repeaters.evidence} onChange={(v) => store.setRepeater('evidence', v)} />;
    }
    if (field.type === 'repeater_workstreams') {
      return <window.WorkstreamRepeater key={field.id} items={store.data.repeaters.workstreams} onChange={(v) => store.setRepeater('workstreams', v)} />;
    }
    return (
      <window.Field
        key={field.id}
        field={field}
        value={store.data.fields[field.id]}
        onChange={store.setField}
        meta={store.data._autofill_meta[field.id]}
        onAccept={store.acceptAutofillForField}
        onClear={store.clearAutofillForField}
        allFields={store.data.fields}
      />
    );
  });

  return (
    <div className="subsection" id={`sub-${sub.id}`}>
      <div className="subsection-header">
        <span className="num">{sub.id}</span>
        <h2>{sub.title}</h2>
      </div>

      {sub.prompt && (
        <div className="consultant-prompt">
          <div className="prompt-label">Consultant prompt — say to client</div>
          <div className="prompt-text">{sub.prompt}</div>
        </div>
      )}

      {sub.probes && <ProbesPanel probes={sub.probes} />}

      {fieldComponents}
    </div>
  );
}

function SectionView({ section, store }) {
  if (section.isDashboard) return <DashboardView store={store} />;

  return (
    <div>
      <div className="section-header">
        <div className="eyebrow">Section {section.id} {section.minutes ? `· ${section.minutes} min` : ''}</div>
        <h1>{section.title}</h1>
        {!section.internal && (
          <div className="meta">
            <span className="chip">⏱ ~{section.minutes} min estimated</span>
            <span className="chip">📋 {section.subs.length} subsection{section.subs.length !== 1 ? 's' : ''}</span>
          </div>
        )}
      </div>

      {section.intro && !section.internal && (
        <div className="section-intro">{section.intro}</div>
      )}

      {section.internal && (
        <div className="section-internal-banner">
          <span className="lock-icon">🔒</span>
          <div>
            <strong>Internal use only — </strong>{section.intro || 'This section does not appear in the client-facing summary.'}
          </div>
        </div>
      )}

      {section.subs.map(sub => (
        <SubsectionCard key={sub.id} section={section} sub={sub} store={store} />
      ))}
    </div>
  );
}

// ---------------------------------------------------------------
// Dashboard (Section 11)
// ---------------------------------------------------------------
function getGradeStyle(gradeId) {
  const g = window.BROOK_SCHEMA.gradeScale.find(x => x.id === gradeId);
  return g ? { color: g.color, background: g.bg, label: g.label } : { color: '#64748b', background: '#f1f5f9', label: 'Not graded' };
}

function getStatusStyle(statusId) {
  const s = window.BROOK_SCHEMA.complianceStatuses.find(x => x.id === statusId);
  return s ? { color: s.color, background: s.bg, label: s.label } : { color: '#64748b', background: '#f1f5f9', label: '—' };
}

function AreaCard({ areaDef, areaData, onChange }) {
  const [open, setOpen] = React.useState(false);
  if (!areaData) return null;
  const grade = getGradeStyle(areaData.suggestedGrade || 'insufficient_evidence');
  const ranAt = areaData.ranAt ? new Date(areaData.ranAt) : null;

  return (
    <div className="area-card">
      <div className="area-head">
        <div className="area-name">{areaDef.name}</div>
        <span className="area-grade" style={{ color: grade.color, background: grade.background }}>{grade.label}</span>
      </div>
      <div className="area-body">
        {areaData.gradeReasoning && <div className="area-grade-reasoning">{areaData.gradeReasoning}</div>}
        {areaData.judgement && <div className="area-judgement">{areaData.judgement}</div>}
        {ranAt && (
          <div style={{ fontSize: 11, color: '#8a93a4', marginTop: 8, letterSpacing: '0.04em' }}>
            ✦ AI ran {ranAt.toLocaleDateString('en-GB', { day: 'numeric', month: 'short' })} {ranAt.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
            {areaData.applied !== false && <span> · applied</span>}
          </div>
        )}
      </div>
      {areaData.indicators && areaData.indicators.length > 0 && (
        <>
          <button className="indicators-toggle" onClick={() => setOpen(!open)}>
            {open ? '▼' : '▶'} {areaData.indicators.length} indicator{areaData.indicators.length !== 1 ? 's' : ''} with evidence
          </button>
          {open && (
            <div className="indicators-list">
              {areaData.indicators.map(ind => {
                const indDef = areaDef.indicators.find(x => x.id === ind.id);
                return (
                  <div className="indicator" key={ind.id}>
                    <div className="indicator-head">
                      <span className="indicator-name">{indDef ? indDef.name : ind.id}</span>
                      <span className={`indicator-conf ${ind.confidence}`}>{(ind.confidence || 'med').toUpperCase()}</span>
                    </div>
                    {ind.evidence && (
                      <ul className="indicator-evidence">
                        {ind.evidence.map((e, i) => <li key={i}>{e}</li>)}
                      </ul>
                    )}
                  </div>
                );
              })}
            </div>
          )}
        </>
      )}
    </div>
  );
}

function EditableList({ items, onChange, placeholder, emptyText }) {
  const [editing, setEditing] = React.useState(false);
  const [text, setText] = React.useState('');
  React.useEffect(() => { setText((items || []).join('\n')); }, [items]);

  if (editing) {
    return (
      <div>
        <textarea className="textarea" rows={Math.max(4, (items || []).length + 2)} value={text} onChange={e => setText(e.target.value)} placeholder={placeholder} style={{ marginBottom: 8 }} />
        <div className="row" style={{ gap: 8 }}>
          <button className="btn btn-primary" onClick={() => { onChange(text.split('\n').map(s => s.trim()).filter(Boolean)); setEditing(false); }}>Save</button>
          <button className="btn" onClick={() => setEditing(false)}>Cancel</button>
        </div>
      </div>
    );
  }
  return (
    <div>
      {(!items || !items.length) && <div className="muted" style={{ fontSize: 13, fontStyle: 'italic', marginBottom: 8 }}>{emptyText || 'No items yet.'}</div>}
      {items && items.length > 0 && (
        <ul style={{ margin: 0, paddingLeft: 20 }}>
          {items.map((item, i) => <li key={i} style={{ fontSize: 13.5, lineHeight: 1.5, padding: '3px 0' }}>{item}</li>)}
        </ul>
      )}
      <button className="btn" style={{ marginTop: 10, fontSize: 12 }} onClick={() => setEditing(true)}>✎ Edit list</button>
    </div>
  );
}

function DashboardView({ store }) {
  // Read from the canonical aiResults tree (mirrors the Ofsted EYFS app shape).
  const ai = store.data.aiResults || {};
  const dashAreas = {};
  Object.keys(ai).forEach(k => {
    if (k !== 'statutory' && k !== 'findings' && k !== 'executive_summary') dashAreas[k] = ai[k];
  });
  const dash = {
    areas: dashAreas,
    compliance: ai.statutory?.findings || [],
    strengths: ai.findings?.strengths || [],
    areas_for_development: ai.findings?.afd || [],
    actions: ai.findings?.actions || [],
    executive_summary: ai.executive_summary || { overall_assessment: '', key_risks: [], immediate_priorities: [] }
  };
  const areas = window.BROOK_SCHEMA.evaluationAreas;
  const compSections = window.BROOK_SCHEMA.complianceSections;
  const hasAny = (dash.areas && Object.keys(dash.areas).length) ||
                 dash.strengths.length || dash.areas_for_development.length ||
                 dash.actions.length || dash.compliance.length;

  return (
    <div>
      <div className="section-header">
        <div className="eyebrow">Section 11 · Assessment Dashboard</div>
        <h1>Assessment Dashboard</h1>
      </div>

      {!hasAny && (
        <div className="empty-state" style={{ padding: '40px 24px' }}>
          <strong style={{ fontSize: 16 }}>Dashboard not yet populated</strong>
          Use <strong>Auto-Complete from Transcript</strong> at the top of the page to generate a full assessment from a meeting summary or transcript. The dashboard can also be filled in manually below.
        </div>
      )}

      {hasAny && (
        <>
          {/* Executive summary */}
          {dash.executive_summary && (dash.executive_summary.overall_assessment || dash.executive_summary.key_risks?.length || dash.executive_summary.immediate_priorities?.length) && (
            <div className="exec-panel">
              <h3>Executive Assessment Summary</h3>
              {dash.executive_summary.overall_assessment && <div className="overall">{dash.executive_summary.overall_assessment}</div>}
              <div className="twocol">
                <div>
                  <h4>Key Risks</h4>
                  <EditableList
                    items={dash.executive_summary.key_risks || []}
                    onChange={list => store.setDashboard(d => ({ ...d, executive_summary: { ...d.executive_summary, key_risks: list } }))}
                    placeholder="One risk per line"
                    emptyText="No key risks identified yet."
                  />
                </div>
                <div>
                  <h4>Immediate Priorities</h4>
                  <EditableList
                    items={dash.executive_summary.immediate_priorities || []}
                    onChange={list => store.setDashboard(d => ({ ...d, executive_summary: { ...d.executive_summary, immediate_priorities: list } }))}
                    placeholder="One priority per line"
                    emptyText="No immediate priorities identified yet."
                  />
                </div>
              </div>
            </div>
          )}

          {/* Areas */}
          {dash.areas && Object.keys(dash.areas).length > 0 && (
            <div style={{ marginTop: 28 }}>
              <h2 style={{ fontSize: 18, marginBottom: 12 }}>Evaluation Areas</h2>
              <div className="dashboard-grid">
                {areas.map(areaDef => {
                  const areaData = dash.areas[areaDef.id];
                  if (!areaData) return null;
                  return <AreaCard key={areaDef.id} areaDef={areaDef} areaData={areaData} />;
                })}
              </div>
            </div>
          )}

          {/* Compliance */}
          {dash.compliance && dash.compliance.length > 0 && (
            <div style={{ marginTop: 28 }}>
              <h2 style={{ fontSize: 18, marginBottom: 12 }}>Compliance & Best Practice Findings</h2>
              {compSections.map(sec => {
                const items = sec.items.map(it => {
                  const found = dash.compliance.find(c => c.id === it.id);
                  return found ? { ...it, ...found } : null;
                }).filter(Boolean);
                if (!items.length) return null;
                return (
                  <div className="compliance-section" key={sec.id}>
                    <h3>{sec.name}</h3>
                    <table className="compliance-table">
                      <thead><tr><th className="item-name">Item</th><th className="status-cell">Status</th><th>Evidence note</th></tr></thead>
                      <tbody>
                        {items.map(item => {
                          const st = getStatusStyle(item.status);
                          return (
                            <tr key={item.id}>
                              <td className="item-name">{item.name}</td>
                              <td className="status-cell"><span className="status-pill" style={{ color: st.color, background: st.background }}>{st.label}</span></td>
                              <td className="note-cell">{item.note || '—'}</td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>
                  </div>
                );
              })}
            </div>
          )}

          {/* Findings */}
          {(dash.strengths.length || dash.areas_for_development.length) && (
            <div className="findings-grid" style={{ marginTop: 28 }}>
              <div className="findings-panel strengths">
                <h3>✓ Key Strengths</h3>
                <EditableList
                  items={dash.strengths || []}
                  onChange={list => store.setDashboard(d => ({ ...d, strengths: list }))}
                  emptyText="No strengths identified yet."
                />
              </div>
              <div className="findings-panel development">
                <h3>△ Areas for Development</h3>
                <EditableList
                  items={dash.areas_for_development || []}
                  onChange={list => store.setDashboard(d => ({ ...d, areas_for_development: list }))}
                  emptyText="No development areas identified yet."
                />
              </div>
            </div>
          )}

          {/* Actions */}
          {dash.actions.length > 0 && (
            <div style={{ marginTop: 18 }}>
              <h2 style={{ fontSize: 18, marginBottom: 12 }}>Action Plan</h2>
              <table className="action-table">
                <thead><tr><th>Action</th><th style={{ width: 140 }}>Owner</th><th style={{ width: 120 }}>Priority</th><th style={{ width: 160 }}>Timeline</th></tr></thead>
                <tbody>
                  {dash.actions.map((a, i) => (
                    <tr key={i}>
                      <td>{a.action}</td>
                      <td>{a.owner || '—'}</td>
                      <td><span className={`priority-pill priority-${a.priority || 'Medium'}`}>{a.priority || 'Medium'}</span></td>
                      <td>{a.timeline || '—'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </>
      )}
    </div>
  );
}

Object.assign(window, { SectionView, DashboardView, getGradeStyle, getStatusStyle });
