/* Results / status view for a single evaluation */
(() => {
const { useEffect: useEffectR, useState: useStateR } = React;

function Results({ publicKey, onReset }) {
  const [ev, setEv] = useStateR(null);
  const [err, setErr] = useStateR('');

  useEffectR(() => {
    let stopped = false;
    async function poll() {
      try {
        const data = await api.getEvaluation(publicKey);
        if (stopped) return;
        setEv(data);
        if (data.status === 'pending' || data.status === 'researching' || data.status === 'scoring') {
          setTimeout(poll, 3000);
        }
      } catch (e) {
        if (!stopped) setErr(e.message);
      }
    }
    poll();
    return () => { stopped = true; };
  }, [publicKey]);

  if (err) return (
    <Card>
      <div className="text-red-700 bg-red-50 border border-red-200 rounded p-4">⚠ {err}</div>
      <button onClick={onReset} className="mt-4 text-sm text-brand">← Back to new evaluation</button>
    </Card>
  );
  if (!ev) return <Card><div className="text-ink-4">Loading…</div></Card>;

  const statusEmoji = {
    pending: '⏳', researching: '🔍', scoring: '🧮', complete: '✅', failed: '⚠️',
  }[ev.status] || '·';

  const verdictClass =
    ev.score_tier === 'sign'    ? 'verdict-sign'    :
    ev.score_tier === 'review'  ? 'verdict-review'  :
    ev.score_tier === 'decline' ? 'verdict-decline' :
    ev.score_tier === 'reject'  ? 'verdict-reject'  : 'bg-gray-100 text-ink-3';

  return (
    <div className="space-y-4">
      <div className="bg-white rounded-2xl shadow-sm border border-gray-200 p-5 flex items-center justify-between">
        <div>
          <div className="text-xs text-ink-4 uppercase tracking-wider">Case</div>
          <div className="text-lg font-bold font-mono">{ev.public_key}</div>
          <div className="text-sm text-ink-3 mt-1">{ev.defendant_name || '—'} vs. {ev.client_name || '—'}</div>
        </div>
        <div className="text-right">
          <div className="text-xs text-ink-4 uppercase tracking-wider">Status</div>
          <div className="text-lg font-semibold">{statusEmoji} {ev.status}</div>
        </div>
      </div>

      {ev.status === 'researching' && <ProgressCard label="Researching defendant — SOS, CourtListener, CFPB, WHOIS, ToS scan" />}
      {ev.status === 'scoring'      && <ProgressCard label="Scoring case against firm rubric" />}

      {ev.status === 'failed' && (
        <Card>
          <div className="text-red-700 bg-red-50 border border-red-200 rounded p-4">
            <strong>Pipeline failed:</strong> {ev.error || 'unknown error'}
          </div>
        </Card>
      )}

      {ev.status === 'complete' && (
        <>
          <div className="bg-white rounded-2xl shadow-sm border border-gray-200 p-6">
            <div className="flex items-start gap-6">
              <div className="text-center">
                <div className="text-5xl font-bold text-ink">{ev.score?.toFixed(1)}</div>
                <div className="text-xs text-ink-4 mt-1">/ 10</div>
              </div>
              <div className="flex-1">
                <div className={`inline-block px-3 py-1 rounded-full text-xs font-bold ${verdictClass}`}>
                  {ev.score_tier?.toUpperCase()}
                </div>
                {ev.score_factors && (
                  <div className="mt-3 space-y-1 text-sm">
                    {ev.score_factors.map((f, i) => (
                      <div key={i} className="flex justify-between text-ink-2">
                        <span>{f.label}</span>
                        <span className={f.delta >= 0 ? 'text-green-700 font-mono' : 'text-red-700 font-mono'}>
                          {f.delta >= 0 ? '+' : ''}{f.delta}
                        </span>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          </div>

          <div className="bg-white rounded-2xl shadow-sm border border-gray-200 p-6">
            <div className="text-xs font-bold text-ink-4 uppercase tracking-wider mb-3">Generated documents</div>
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
              <DocButton href={api.downloadUrl(ev.public_key, 'demand')}  label="Demand letter"      icon="📄" sub="docx" />
              <DocButton href={api.downloadUrl(ev.public_key, 'exhibits')} label="Evidence exhibits" icon="📎" sub="pdf"  />
              <DocButton href={api.downloadUrl(ev.public_key, 'report')}   label="Case report"       icon="📊" sub="pdf"  />
            </div>
          </div>

          {ev.case_summary && (
            <div className="bg-white rounded-2xl shadow-sm border border-gray-200 p-6">
              <div className="text-xs font-bold text-ink-4 uppercase tracking-wider mb-3">Full case summary</div>
              <pre className="text-[13px] whitespace-pre-wrap font-sans text-ink-2 leading-6">{ev.case_summary}</pre>
            </div>
          )}
        </>
      )}

      <button onClick={onReset} className="text-sm text-brand hover:text-brand-dark">
        ← Start another evaluation
      </button>
    </div>
  );
}

function Card({ children }) {
  return <div className="bg-white rounded-2xl shadow-sm border border-gray-200 p-6">{children}</div>;
}
function ProgressCard({ label }) {
  return (
    <div className="bg-white rounded-2xl shadow-sm border border-gray-200 p-6 flex items-center gap-3">
      <div className="w-3 h-3 rounded-full bg-brand animate-pulse"></div>
      <div className="text-sm text-ink-2">{label}…</div>
    </div>
  );
}
function DocButton({ href, label, icon, sub }) {
  return (
    <a href={href} className="border border-gray-200 rounded-lg p-3 hover:border-brand hover:bg-green-50 transition group">
      <div className="text-2xl mb-1">{icon}</div>
      <div className="text-sm font-semibold text-ink">{label}</div>
      <div className="text-[11px] text-ink-4 group-hover:text-brand">{sub} ↓</div>
    </a>
  );
}

window.Results = Results;
})();
