// Brook Consultancy — Auto-Complete modal, Quick Capture, Reports

// ---------------------------------------------------------------
// AUTO-COMPLETE FROM TRANSCRIPT MODAL
// ---------------------------------------------------------------
function AutoCompleteModal({ open, onClose, onApply, initialSummary, initialTranscript }) {
  const [summary, setSummary] = React.useState(initialSummary || '');
  const [transcript, setTranscript] = React.useState(initialTranscript || '');
  const [running, setRunning] = React.useState(false);
  const [stage, setStage] = React.useState(null);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    if (open) {
      setSummary(initialSummary || '');
      setTranscript(initialTranscript || '');
    }
  }, [open, initialSummary, initialTranscript]);

  if (!open) return null;

  const stages = [
    { key: 'preparing', label: 'Preparing analysis prompt' },
    { key: 'analysing', label: 'AI analysing source content' },
    { key: 'parsing', label: 'Parsing structured findings' },
    { key: 'mapping', label: 'Mapping findings to consultation fields' }
  ];

  const stageStatus = (k) => {
    const ki = stages.findIndex(s => s.key === k);
    const ci = stages.findIndex(s => s.key === stage);
    if (ki < ci) return 'done';
    if (ki === ci) return 'active';
    return '';
  };

  const run = async () => {
    setError(null);
    if (!summary.trim() && !transcript.trim()) {
      setError('Please paste a meeting summary or transcript before running analysis.');
      return;
    }
    setRunning(true);
    try {
      const result = await window.runBrookAnalysis(summary, transcript, setStage);
      // Pass through the literal source content so it can be persisted as aiSummary/aiTranscript
      onApply({ ...result, summary, transcript });
      onClose();
    } catch (e) {
      setError(e.message || String(e));
      setRunning(false);
      setStage(null);
    }
  };

  const loadDemo = () => {
    setSummary(window.BROOK_DEMO_TRANSCRIPT.split('TRANSCRIPT EXCERPTS:')[0]);
    setTranscript(window.BROOK_DEMO_TRANSCRIPT.split('TRANSCRIPT EXCERPTS:')[1] || '');
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 1080 }}>
        <div className="modal-header">
          <div>
            <h2>Auto-Complete from Transcript</h2>
            <div className="modal-sub">Analyse a meeting summary or transcript to pre-populate the consultation record</div>
          </div>
          <button className="close-btn" onClick={onClose} disabled={running}>×</button>
        </div>

        <div className="modal-body">
          {!running && (
            <>
              <div className="autocomplete-intro">
                Paste a <strong>meeting summary</strong>, an <strong>executive briefing</strong>, or the <strong>full transcript</strong> from your initial consultation. The Brook analysis engine will extract evidence and populate the consultation record. <strong>Findings are highlighted in amber for your review</strong> — nothing is invented; if there's no evidence, the field is left blank.
              </div>

              {error && (
                <div className="app-banner error" style={{ borderRadius: 6, marginBottom: 12, borderBottomColor: '#f0bfb9' }}>
                  <span><strong>Error:</strong> {error}</span>
                  <button className="dismiss" onClick={() => setError(null)}>×</button>
                </div>
              )}

              <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 6 }}>
                <button className="demo-link" onClick={loadDemo}>Load worked example (Westbrook Care Home)</button>
              </div>

              <div className="autocomplete-grid">
                <div>
                  <div className="autocomplete-label">
                    <span>Executive Summary / Meeting Notes</span>
                    <span className="opt">{summary.length} chars</span>
                  </div>
                  <textarea
                    className="autocomplete-textarea"
                    value={summary}
                    onChange={e => setSummary(e.target.value)}
                    placeholder="Paste the meeting summary, executive notes, or call recap here..."
                  />
                </div>
                <div>
                  <div className="autocomplete-label">
                    <span>Full Transcript <span style={{ color: '#8a93a4', fontWeight: 400 }}>(optional)</span></span>
                    <span className="opt">{transcript.length} chars</span>
                  </div>
                  <textarea
                    className="autocomplete-textarea"
                    value={transcript}
                    onChange={e => setTranscript(e.target.value)}
                    placeholder="Paste the verbatim meeting transcript here for the most detailed analysis..."
                  />
                </div>
              </div>
            </>
          )}

          {running && (
            <div className="analysis-status">
              <div className="analysis-spinner"></div>
              <h3>Analysing consultation source</h3>
              <p>The Brook analysis engine is reviewing the source against 7 evaluation areas, 28 indicators, and 24 compliance checks. This typically takes 20–40 seconds.</p>
              <div className="analysis-stages">
                {stages.map(s => (
                  <div key={s.key} className={`analysis-stage ${stageStatus(s.key)}`}>
                    <span className="dot"></span>
                    <span>{s.label}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        <div className="modal-footer">
          <div className="left">
            🔒 Source content is sent to the AI engine for analysis only. No data is stored externally. Output is for the consultant's review.
          </div>
          <div className="actions">
            <button className="btn" onClick={onClose} disabled={running}>Cancel</button>
            <button className="btn btn-amber" onClick={run} disabled={running || (!summary.trim() && !transcript.trim())}>
              {running ? 'Analysing…' : '✦ Run Analysis'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------
// QUICK CAPTURE PANEL
// ---------------------------------------------------------------
function QuickCapture() {
  const qc = window.useQuickCapture();
  const [open, setOpen] = React.useState(false);
  const [text, setText] = React.useState('');
  const taRef = React.useRef(null);

  const submit = () => {
    if (!text.trim()) return;
    qc.add(text);
    setText('');
    if (taRef.current) taRef.current.focus();
  };

  const onKey = (e) => {
    if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
      e.preventDefault();
      submit();
    }
  };

  if (!open) {
    return (
      <button className="qc-fab" onClick={() => setOpen(true)} title="Quick Capture (Cmd/Ctrl+K)">
        <span className="icon">✎</span>
        Quick Capture
        {qc.items.length > 0 && <span className="badge">{qc.items.length}</span>}
      </button>
    );
  }

  return (
    <div className="qc-panel">
      <div className="qc-header">
        <div>
          <h3>Quick Capture</h3>
          <div className="qc-sub">Scratchpad for anything that comes up out of order</div>
        </div>
        <button className="qc-close" onClick={() => setOpen(false)}>×</button>
      </div>
      <div className="qc-list">
        {qc.items.length === 0 && <div className="qc-empty">Nothing captured yet.<br/>Use the box below for thoughts you want to come back to.</div>}
        {qc.items.map(item => {
          const t = new Date(item.created);
          return (
            <div key={item.id} className="qc-item">
              <div className="qc-time">{t.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</div>
              <div className="qc-text">{item.text}</div>
              <button className="qc-del" onClick={() => qc.remove(item.id)}>×</button>
            </div>
          );
        })}
      </div>
      <div className="qc-input">
        <textarea
          ref={taRef}
          value={text}
          onChange={e => setText(e.target.value)}
          onKeyDown={onKey}
          placeholder="Anything to come back to..."
          autoFocus
        />
        <button onClick={submit}>Add</button>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------
// CONSULTATION LOG (v2 — multi-record with sync indicators + claim & open)
// ---------------------------------------------------------------
function ConsultationLog({ log, activeRecordId, onClose, onLoad, onClaim, onDelete, onNew }) {
  const statusMeta = window.statusMeta || (() => ({ label: 'In progress', color: '#1e6091', bg: '#e2eef7' }));
  const driveConfigured = !!(window.loadDriveSettings && window.loadDriveSettings().clientId);

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 1180 }}>
        <div className="modal-header">
          <div>
            <h2>Consultation Log</h2>
            <div className="modal-sub">All consultations stored on this device — synced via Google Drive when connected</div>
          </div>
          <button className="close-btn" onClick={onClose}>×</button>
        </div>
        <div className="modal-body" style={{ padding: 20 }}>
          {log.length === 0 && (
            <div className="empty-state" style={{ padding: '40px 24px' }}>
              <strong>No consultations yet</strong>
              Start a new consultation to capture notes — it will appear here automatically and sync to the shared drive if Drive sync is configured.
            </div>
          )}
          {log.length > 0 && (
            <table className="log-table">
              <thead>
                <tr>
                  {driveConfigured && <th style={{ width: 28 }}></th>}
                  <th>Organisation</th>
                  <th>Client</th>
                  <th>Date</th>
                  <th>Type</th>
                  <th>Lead</th>
                  <th>Status</th>
                  <th>Updated</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {log.map(entry => {
                  const sm = statusMeta(entry.status);
                  const isActive = entry.id === activeRecordId;
                  const isWaiting = entry.status === 'ready_for_analysis';
                  return (
                    <tr key={entry.id} style={isActive ? { background: 'rgba(44,122,123,0.04)' } : undefined}>
                      {driveConfigured && (
                        <td title={entry.fileId ? 'Synced to Drive' : 'Not yet synced'} style={{ textAlign: 'center', color: entry.fileId ? 'var(--brook-teal)' : 'var(--text-muted)' }}>
                          {entry.fileId ? '☁' : '○'}
                        </td>
                      )}
                      <td>
                        <strong>{entry.org_name}</strong>
                        {entry.consultant_name && <div style={{ fontSize: 11, color: '#8a93a4' }}>by {entry.consultant_name}</div>}
                        <div style={{ display: 'flex', gap: 8, marginTop: 2 }}>
                          {entry.autofill_used && <span style={{ fontSize: 10.5, color: 'var(--brook-amber)', fontWeight: 600 }}>✦ AI-assisted</span>}
                          {entry.audio?.fileId && <span style={{ fontSize: 10.5, color: 'var(--brook-teal)', fontWeight: 600 }} title={`Audio recording attached (${window.fmtDuration ? window.fmtDuration(entry.audio.durationSec) : entry.audio.durationSec + 's'})`}>✎ Audio</span>}
                          {entry.audio?.uploadStatus === 'uploading' && <span style={{ fontSize: 10.5, color: '#5eaaab', fontWeight: 600 }}>✎ Uploading {entry.audio.uploadProgress || 0}%</span>}
                          {entry.audio?.uploadStatus === 'failed' && <span style={{ fontSize: 10.5, color: 'var(--danger)', fontWeight: 600 }}>✎ Audio upload failed</span>}
                        </div>
                      </td>
                      <td>{entry.client_name || '—'}</td>
                      <td>{entry.consultation_date || '—'}</td>
                      <td style={{ fontSize: 12.5 }}>{entry.org_type || '—'}</td>
                      <td>{entry.lead_priority ? <span className={`lead-pill lead-${entry.lead_priority.replace(' ', '-')}`}>{entry.lead_priority}</span> : '—'}</td>
                      <td>
                        <span style={{ display: 'inline-block', padding: '3px 9px', borderRadius: 10, fontSize: 11, fontWeight: 600, color: sm.color, background: sm.bg, letterSpacing: '0.03em' }}>
                          {sm.label}
                        </span>
                        {entry.claimedBy && <div style={{ fontSize: 10.5, color: 'var(--text-muted)', marginTop: 2 }}>claimed</div>}
                      </td>
                      <td style={{ fontSize: 11, color: 'var(--text-muted)' }}>
                        {entry.updatedAt ? new Date(entry.updatedAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '—'}
                      </td>
                      <td style={{ whiteSpace: 'nowrap' }}>
                        {isWaiting && onClaim && (
                          <button className="btn btn-amber" style={{ padding: '4px 10px', fontSize: 12, marginRight: 4 }} onClick={() => onClaim(entry.id)}>
                            Claim &amp; open
                          </button>
                        )}
                        <button className="btn" style={{ padding: '4px 10px', fontSize: 12, marginRight: 4 }} onClick={() => onLoad(entry.id)} disabled={isActive}>
                          {isActive ? 'Active' : 'Open'}
                        </button>
                        {onDelete && (
                          <button className="btn" style={{ padding: '4px 8px', fontSize: 12, color: 'var(--danger)', borderColor: '#e3b9b3' }} onClick={() => onDelete(entry.id)} title="Delete">×</button>
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          )}
        </div>
        <div className="modal-footer">
          <div className="left">{log.length} consultation{log.length !== 1 ? 's' : ''} on file{driveConfigured ? ' · ☁ = synced' : ''}</div>
          <div className="actions">
            <button className="btn btn-primary" onClick={onNew}>+ New Consultation</button>
            <button className="btn" onClick={onClose}>Close</button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AutoCompleteModal, QuickCapture, ConsultationLog });
