// Renders a public, read-only result page from a share token (#/r/:token).
// Fetches /api/r/:token via window.AppData.getSharedRun, then renders the
// same rich UI an authenticated user sees on their own result page — minus
// auth-only actions (Save, feedback). The "shared view" intent is reinforced
// with a banner + a primary CTA to run the same diagnostic yourself.
//
// Two rendering paths, same shell:
//   1. Canonical WorkAppRunOutput → verdict card, findings cards (with
//      priority pills + evidence), recommendation block.
//   2. Workflow that returns a raw `output.html` blob → render it inside a
//      sandboxed iframe so the workapp's custom UI shows through.
// The expert card + run-it-yourself CTA show in both paths.
(function () {
  const { useState, useEffect, useRef } = React;

  function HtmlFrame({ html }) {
    const iframeRef = useRef(null);
    const [height, setHeight] = useState(600);
    useEffect(function () {
      const iframe = iframeRef.current;
      if (!iframe) return;
      const doc = iframe.contentDocument;
      if (!doc) return;
      doc.open();
      doc.write('<!doctype html><html><head><meta charset="utf-8"><style>body{margin:0;padding:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}</style></head><body>' + html + '</body></html>');
      doc.close();
      const measure = function () {
        try {
          const h = doc.documentElement.scrollHeight || doc.body.scrollHeight || 600;
          setHeight(h + 24);
        } catch (e) { /* ignore */ }
      };
      measure();
      setTimeout(measure, 50);
      setTimeout(measure, 200);
    }, [html]);
    return React.createElement('iframe', {
      ref: iframeRef,
      sandbox: 'allow-same-origin',
      style: { width: '100%', border: 'none', display: 'block', height: height + 'px' },
      title: 'Shared result',
    });
  }

  function priorityPill(priority) {
    const p = (priority || '').toLowerCase();
    const map = {
      high: { label: 'Fix first', bg: '#fef2f2', fg: '#b91c1c', border: '#fecaca' },
      medium: { label: 'Worth a look', bg: '#fffbeb', fg: '#b45309', border: '#fde68a' },
      low: { label: 'Nice-to-have', bg: '#f0fdf4', fg: '#15803d', border: '#bbf7d0' },
    };
    return map[p] || { label: 'Finding', bg: '#f3f4f6', fg: '#374151', border: '#e5e7eb' };
  }

  function SharedResultScreen({ token }) {
    const [data, setData] = useState(null);
    const [err, setErr] = useState(null);

    useEffect(function () {
      let cancelled = false;
      window.AppData.getSharedRun(token)
        .then(function (d) { if (!cancelled) setData(d); })
        .catch(function (e) { if (!cancelled) setErr(e); });
      return function () { cancelled = true; };
    }, [token]);

    if (err) {
      return (
        <div className="wrap" style={{paddingTop: 80}}>
          <h1 className="serif">This shared result isn't available.</h1>
          <p style={{color: 'var(--muted)'}}>The link may have been revoked, or the result was never shared. Ask the person who sent it for a new link.</p>
        </div>
      );
    }
    if (!data || !data.result) {
      return <div className="loading" style={{padding: 40}}>Loading shared result…</div>;
    }
    const r = data.result;
    const slug = data.workappSlug;
    const hasHtml = typeof r.html === 'string' && r.html.length > 0;
    const hasCanonical = (r.verdictHeadline && r.verdictHeadline.length > 0)
      || (Array.isArray(r.findings) && r.findings.length > 0);

    const runItYourselfHref = slug ? '#/w/' + encodeURIComponent(slug) : '#/workapps';
    const expertInitials = (r.expertName || '?').split(/\s+/).map(function (s) { return s[0]; }).slice(0, 2).join('').toUpperCase();

    return (
      <div className="result-page" data-screen-label="Shared result">
        <div className="wrap">

          <div className="section-label" style={{marginTop: 24}}>
            Shared diagnostic{r.expertName ? ' · Method by ' + r.expertName : ''}
          </div>
          <h1 className="serif" style={{fontSize: 38, lineHeight: 1.15, margin: '8px 0 12px'}}>
            {r.workappTitle || 'A shared WorkApp result'}
          </h1>
          {r.workappSubtitle && (
            <p style={{color: 'var(--muted)', fontSize: 16, lineHeight: 1.5, maxWidth: 680, marginBottom: 24}}>
              {r.workappSubtitle}
            </p>
          )}

          <div style={{
            display: 'flex', flexWrap: 'wrap', gap: 12, alignItems: 'center', justifyContent: 'space-between',
            padding: '14px 18px', borderRadius: 12, background: '#f5f7ff',
            border: '1px solid #dde2ff', margin: '8px 0 32px',
          }}>
            <div style={{flex: '1 1 auto', minWidth: 220}}>
              <div style={{fontSize: 12, fontWeight: 600, letterSpacing: '.04em', textTransform: 'uppercase', color: '#4338ca'}}>You're viewing a shared result</div>
              <div style={{fontSize: 14, color: '#1e1b4b', marginTop: 2}}>
                Run the same diagnostic on your own work in ~60 seconds — no sign-up needed.
              </div>
            </div>
            <a className="btn btn-primary btn-sm" href={runItYourselfHref}>Run it yourself →</a>
          </div>

          {hasCanonical && (
            <>
              <div className="verdict" style={{marginBottom: 24}}>
                <div className="verdict-label">Verdict</div>
                <h2 className="verdict-line serif" style={{fontSize: 28, lineHeight: 1.25, margin: '8px 0'}}>{r.verdictHeadline}</h2>
                {r.verdictSub && <p className="verdict-sub" style={{color: 'var(--muted)', fontSize: 15, marginTop: 6}}>{r.verdictSub}</p>}
                {(r.confidence || r.basis) && (
                  <div style={{display: 'flex', gap: 16, flexWrap: 'wrap', marginTop: 14, fontSize: 12, color: 'var(--muted)'}}>
                    {r.confidence && <div><b style={{color: 'var(--ink)'}}>Confidence:</b> {r.confidence}</div>}
                    {r.basis && <div><b style={{color: 'var(--ink)'}}>Scope:</b> {r.basis}</div>}
                  </div>
                )}
              </div>

              {r.recommendation && (
                <div className="recommendation-block" style={{
                  background: '#fff', border: '1px solid var(--hair-2)', borderLeft: '4px solid #10b981',
                  borderRadius: 12, padding: '18px 22px', margin: '8px 0 28px',
                }}>
                  <div className="block-h" style={{fontSize: 11, fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase', color: '#10b981', marginBottom: 8}}>Recommendation</div>
                  <p style={{fontSize: 15, lineHeight: 1.55, color: 'var(--ink)', margin: 0}}>{r.recommendation}</p>
                </div>
              )}

              {Array.isArray(r.findings) && r.findings.length > 0 && (
                <>
                  <h3 style={{fontSize: 18, fontWeight: 600, margin: '32px 0 14px'}}>
                    {r.findings.length} {r.findings.length === 1 ? 'Finding' : 'Findings'}
                  </h3>
                  <div style={{display: 'flex', flexDirection: 'column', gap: 12}}>
                    {r.findings.map(function (f, i) {
                      const pill = priorityPill(f.priority);
                      return (
                        <div key={i} style={{
                          background: '#fff', border: '1px solid var(--hair-2)', borderRadius: 12,
                          padding: '16px 18px', boxShadow: '0 1px 2px rgba(0,0,0,.03)',
                          display: 'flex', gap: 14, alignItems: 'flex-start',
                        }}>
                          <span style={{
                            flexShrink: 0, fontSize: 11, fontWeight: 700, letterSpacing: '.04em',
                            padding: '4px 8px', borderRadius: 999,
                            background: pill.bg, color: pill.fg, border: '1px solid ' + pill.border,
                            whiteSpace: 'nowrap',
                          }}>{pill.label}</span>
                          <div style={{flex: 1}}>
                            <div style={{fontSize: 15, fontWeight: 600, color: 'var(--ink)', marginBottom: 4}}>{f.title}</div>
                            {f.why && <p style={{fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.55, margin: '4px 0'}}>{f.why}</p>}
                            {f.evidence && (
                              <blockquote style={{
                                margin: '10px 0', padding: '8px 14px', borderLeft: '3px solid var(--hair-2)',
                                fontSize: 13, fontStyle: 'italic', color: 'var(--muted)', lineHeight: 1.5,
                              }}>
                                "{f.evidence}"
                                {f.evidenceSrc && <div style={{fontSize: 11, fontStyle: 'normal', marginTop: 4, color: '#9ca3af'}}>— {f.evidenceSrc}</div>}
                              </blockquote>
                            )}
                            {f.action && (
                              <div style={{fontSize: 13, marginTop: 6, color: 'var(--ink)'}}>
                                <b>Fix:</b> {f.action}
                              </div>
                            )}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </>
              )}
            </>
          )}

          {hasHtml && !hasCanonical && (
            <div style={{
              background: '#fff', border: '1px solid var(--hair-2)', borderRadius: 12,
              overflow: 'hidden', margin: '8px 0 28px',
            }}>
              <HtmlFrame html={r.html} />
            </div>
          )}

          {!hasHtml && !hasCanonical && (
            <p style={{color: 'var(--muted)', marginTop: 24}}>This result didn't include displayable content.</p>
          )}

          {r.expertName && (
            <div style={{
              marginTop: 36, padding: '20px 22px', background: '#fafafa',
              border: '1px solid var(--hair-2)', borderRadius: 12,
              display: 'flex', gap: 16, alignItems: 'flex-start',
            }}>
              {r.expertPhotoUrl ? (
                <img src={r.expertPhotoUrl} alt={r.expertName} style={{width: 56, height: 56, borderRadius: '50%', objectFit: 'cover', flexShrink: 0}} />
              ) : (
                <div style={{
                  width: 56, height: 56, borderRadius: '50%', background: '#111', color: '#fff',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 18, fontWeight: 600, flexShrink: 0,
                }}>{expertInitials}</div>
              )}
              <div style={{flex: 1, minWidth: 0}}>
                <div style={{fontSize: 11, fontWeight: 600, letterSpacing: '.04em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 4}}>
                  Method by
                </div>
                <div style={{fontSize: 17, fontWeight: 600, color: 'var(--ink)'}}>{r.expertName}</div>
                {r.expertTitle && <div style={{fontSize: 13, color: 'var(--muted)', marginTop: 2}}>{r.expertTitle}</div>}
                {r.expertBioShort && <p style={{fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.5, margin: '10px 0 0'}}>{r.expertBioShort}</p>}
                {r.expertProofLine && <div style={{fontSize: 12, color: 'var(--muted)', marginTop: 8}}><b style={{color: 'var(--ink-2)'}}>Proof:</b> {r.expertProofLine}</div>}
              </div>
            </div>
          )}

          <div style={{
            margin: '36px 0 60px', padding: '24px 24px', borderRadius: 12,
            background: 'linear-gradient(135deg, #111 0%, #1f1f24 100%)', color: '#fff',
            display: 'flex', flexWrap: 'wrap', gap: 16, alignItems: 'center', justifyContent: 'space-between',
          }}>
            <div style={{flex: '1 1 auto', minWidth: 240}}>
              <div style={{fontSize: 12, fontWeight: 600, letterSpacing: '.06em', textTransform: 'uppercase', color: '#9ca3af', marginBottom: 4}}>
                Try it on your own
              </div>
              <div style={{fontSize: 18, fontWeight: 600, lineHeight: 1.35}}>
                Get the same diagnostic for your work in ~60 seconds.
              </div>
            </div>
            <a className="btn btn-primary" href={runItYourselfHref} style={{background: '#fff', color: '#111', borderColor: '#fff'}}>
              Run this WorkApp →
            </a>
          </div>
        </div>
      </div>
    );
  }

  window.SharedResultScreen = SharedResultScreen;
})();
