/* ════════════════════════════════════════════════════════
   InstantVisibilityCheck Widget
   ─────────────────────────────────────────────────────────
   Calls /api/visibility-check (Vercel serverless → live AI search).
   Real live AI search, not a simulation.
   ═══════════════════════════════════════════════════════ */

const PROCEDURES = [
  'Rhinoplasty', 'Breast Augmentation', 'Facelift',
  'Mommy Makeover', 'BBL', 'Body Contouring', 'Non-Surgical'
];

// Mirrors server-side scaling in /api/visibility-check.js so the form can
// preview the exact total count before submission.
function queriesPerProcedure(count) {
  if (count <= 1) return 5;
  if (count === 2) return 4;
  if (count <= 4) return 3;
  return 2;
}

const SAFE_RE = /^[A-Za-z0-9\s\-'.,&]+$/;
const sanitize = (s) => String(s || '').trim().slice(0, 80);

async function fetchVisibility({ practice, surgeon, zip, procedures, email }) {
  const response = await fetch('/api/visibility-check', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      practice_name: practice,
      surgeon_name: surgeon || null,
      zip,
      procedures,
      email: email.trim()
    })
  });
  if (!response.ok) {
    let err;
    try { err = await response.json(); } catch (e) { err = { error: 'Request failed' }; }
    throw new Error(err.error || 'Something went wrong');
  }
  return await response.json();
}

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

function InstantVisibilityCheck({ gold }) {
  const [stage, setStage] = React.useState('form');
  const [form, setForm] = React.useState({
    practice: '',
    surgeon: '',
    zip: '',
    procedures: ['Rhinoplasty']
  });
  const [leadEmail, setLeadEmail] = React.useState('');
  const [error, setError] = React.useState('');
  const [result, setResult] = React.useState(null);
  const [email, setEmail] = React.useState('');
  const [emailErr, setEmailErr] = React.useState('');

  const fieldStyle = {
    fontFamily: "'SF Pro Text','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 14,
    color: '#FAFAF8', background: 'rgba(255,255,255,0.04)',
    border: '1px solid rgba(250,250,248,0.12)', borderRadius: 10,
    padding: '12px 16px', outline: 'none', width: '100%',
    transition: 'border-color 0.2s, background 0.2s',
  };

  function toggleProcedure(p) {
    setForm(f => {
      const has = f.procedures.includes(p);
      const next = has ? f.procedures.filter(x => x !== p) : [...f.procedures, p];
      return { ...f, procedures: next };
    });
  }

  function handleSubmit(e) {
    e.preventDefault();
    const practice = sanitize(form.practice);
    const surgeon = sanitize(form.surgeon);
    const zip = sanitize(form.zip);

    if (practice.length < 2 || practice.length > 80) return setError('Please enter your practice name (2–80 characters).');
    if (!/^\d{5}$/.test(zip)) return setError('Please enter a valid 5-digit US ZIP code.');
    if (surgeon && surgeon.length > 80) return setError('Surgeon name too long.');
    if (!SAFE_RE.test(practice)) return setError('Practice name has invalid characters.');
    if (surgeon && !SAFE_RE.test(surgeon)) return setError('Surgeon name has invalid characters.');
    if (form.procedures.length === 0) return setError('Select at least one procedure.');
    if (form.procedures.some(p => !PROCEDURES.includes(p))) return setError('Invalid procedure.');
    if (!EMAIL_RE.test(leadEmail.trim())) return setError('Please enter a valid work email.');

    setError('');
    setStage('loading');
    fetchVisibility({ practice, surgeon, zip, procedures: form.procedures, email: leadEmail })
      .then((res) => {
        setResult({ ...res, practice, surgeon, zip, procedures: form.procedures, leadEmail: leadEmail.trim() });
        setStage('results');
      })
      .catch((err) => {
        setError(err.message || 'Something went wrong. Please try again.');
        setStage('form');
      });
  }

  function handleClaim(e) {
    e.preventDefault();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return setEmailErr('Enter a valid email.');
    setEmailErr('');
    try {
      const payload = { ...result, email, ts: new Date().toISOString() };
      const KEY = 'arc_audit_claims';
      const arr = JSON.parse(localStorage.getItem(KEY) || '[]');
      arr.push(payload); localStorage.setItem(KEY, JSON.stringify(arr));
    } catch(e) {}
    setStage('submitted');
  }

  function reset() {
    setStage('form'); setResult(null); setEmail(''); setLeadEmail('');
    setForm({ practice: '', surgeon: '', zip: '', procedures: ['Rhinoplasty'] });
  }

  // ── FORM ─────────────────────────────────────────────────
  if (stage === 'form') {
    const procCount = form.procedures.length;
    const perProc = queriesPerProcedure(procCount);
    const totalQueries = procCount * perProc;
    return (
      <div className="glass-strong" style={{ borderRadius: 20, padding: '32px 36px', maxWidth: 720, margin: '0 auto', textAlign: 'left' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
          <span style={{ width: 8, height: 8, borderRadius: '50%', background: gold, boxShadow: `0 0 8px ${gold}` }} />
          <span style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10.5, letterSpacing: '0.2em', textTransform: 'uppercase', color: gold }}>Live AI Check · Powered by Perplexity</span>
        </div>
        <div style={{ fontFamily: "'SF Pro Display','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 24, fontWeight: 700, fontStyle: 'italic', color: '#FAFAF8', marginBottom: 10, letterSpacing: '-0.02em' }}>
          See if AI recommends your practice. Free. 30 seconds.
        </div>
        <p style={{ fontFamily: "'SF Pro Text','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 14, color: 'rgba(250,250,248,0.65)', lineHeight: 1.6, marginTop: 0, marginBottom: 22 }}>
          Enter your practice name, ZIP code, and the procedures you offer. Live searches run on Perplexity right now — and show you exactly what patients see when they ask AI for a surgeon, including who it recommends instead of you.
        </p>
        <form onSubmit={handleSubmit} style={{ display: 'grid', gap: 14 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <input style={fieldStyle} placeholder="Practice Name (e.g. Smith Aesthetic)" value={form.practice} onChange={e => setForm({ ...form, practice: e.target.value })} maxLength={80} />
            <input style={fieldStyle} placeholder="ZIP code (5 digits)" value={form.zip} onChange={e => setForm({ ...form, zip: e.target.value.replace(/\D/g, '').slice(0, 5) })} maxLength={5} inputMode="numeric" />
          </div>
          <input style={fieldStyle} placeholder="Lead Surgeon Name (optional)" value={form.surgeon} onChange={e => setForm({ ...form, surgeon: e.target.value })} maxLength={80} />
          <input style={fieldStyle} type="email" placeholder="Work email — where to send the report" value={leadEmail} onChange={e => setLeadEmail(e.target.value)} maxLength={200} autoComplete="email" />

          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
              <span style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'rgba(250,250,248,0.55)' }}>Procedures you offer</span>
              <span style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, letterSpacing: '0.16em', color: 'rgba(250,250,248,0.4)' }}>
                {procCount} selected
              </span>
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {PROCEDURES.map(p => {
                const selected = form.procedures.includes(p);
                return (
                  <button type="button" key={p} onClick={() => toggleProcedure(p)} style={{
                    fontFamily: "'SF Pro Text','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 13, fontWeight: 500,
                    padding: '8px 14px', borderRadius: 9999, cursor: 'pointer',
                    background: selected ? gold : 'rgba(255,255,255,0.04)',
                    color: selected ? '#0A0A0A' : 'rgba(250,250,248,0.7)',
                    border: selected ? `1px solid ${gold}` : '1px solid rgba(250,250,248,0.12)',
                    transition: 'all 0.18s',
                  }}>{p}</button>
                );
              })}
            </div>
            <div style={{ fontFamily: "'SF Pro Text','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 11.5, color: 'rgba(250,250,248,0.45)', marginTop: 8 }}>
              {procCount === 0
                ? 'Select at least one procedure.'
                : `${procCount} procedure${procCount === 1 ? '' : 's'} × ${perProc} patient ${perProc === 1 ? 'query' : 'queries'} = ${totalQueries} live AI searches`}
            </div>
          </div>

          {error && <div style={{ fontFamily: "'SF Pro Text','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 13, color: '#E07A5F' }}>{error}</div>}
          <button type="submit" className="btn-gold" disabled={!EMAIL_RE.test(leadEmail.trim())} style={{ justifyContent: 'center', marginTop: 4, opacity: EMAIL_RE.test(leadEmail.trim()) ? 1 : 0.5, cursor: EMAIL_RE.test(leadEmail.trim()) ? 'pointer' : 'not-allowed' }}>
            <span>Run Instant Check →</span>
          </button>
        </form>
      </div>
    );
  }

  // ── LOADING ──────────────────────────────────────────────
  if (stage === 'loading') {
    const procCount = form.procedures.length;
    const total = procCount * queriesPerProcedure(procCount);
    return (
      <div className="glass-strong" style={{ borderRadius: 20, padding: '48px 36px', maxWidth: 720, margin: '0 auto', textAlign: 'center' }}>
        <svg width="80" height="40" viewBox="0 0 80 40" style={{ display: 'block', margin: '0 auto 24px' }}>
          <path d="M 4 36 Q 20 4 40 4 Q 60 4 76 36" stroke={gold} strokeWidth="2" fill="none" strokeLinecap="round"
            strokeDasharray="120" strokeDashoffset="120">
            <animate attributeName="stroke-dashoffset" from="120" to="-120" dur="1.6s" repeatCount="indefinite" />
          </path>
        </svg>
        <div style={{ fontFamily: "'SF Pro Display','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 22, fontStyle: 'italic', color: '#FAFAF8', marginBottom: 8 }}>
          Running 5 live searches per procedure on Perplexity…
        </div>
        <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, letterSpacing: '0.15em', textTransform: 'uppercase', color: 'rgba(250,250,248,0.5)' }}>
          {form.procedures.join(' · ')} · {sanitize(form.zip)}
        </div>
        <div style={{ fontFamily: "'SF Pro Text','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 12, color: 'rgba(250,250,248,0.4)', marginTop: 16, lineHeight: 1.5 }}>
          Live web search. This takes 15–30 seconds.
        </div>
      </div>
    );
  }

  // ── SUBMITTED ────────────────────────────────────────────
  if (stage === 'submitted') {
    return (
      <div className="glass-strong" style={{ borderRadius: 20, padding: '48px 36px', maxWidth: 720, margin: '0 auto', textAlign: 'center' }}>
        <div style={{ width: 56, height: 56, borderRadius: '50%', border: `2px solid ${gold}`, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 20px', color: gold, fontSize: 28 }}>✓</div>
        <div style={{ fontFamily: "'SF Pro Display','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 28, fontStyle: 'italic', color: '#FAFAF8', marginBottom: 14, letterSpacing: '-0.02em' }}>
          Your full Citation Gap Report will arrive within 7 days.
        </div>
        <div style={{ fontFamily: "'SF Pro Text','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 14, color: 'rgba(250,250,248,0.65)', marginBottom: 24 }}>
          50 queries × 4 AI engines · named-competitor analysis · five specific opportunities minimum.
        </div>
        <button onClick={reset} className="btn-ghost">Run another check</button>
      </div>
    );
  }

  // ── RESULTS ──────────────────────────────────────────────
  const score = result.score;
  const scoreColor = score === 0 ? '#E07A5F' : score >= 67 ? gold : '#D9A66B';

  // Group queries by procedure
  const grouped = {};
  result.results.forEach(q => {
    (grouped[q.procedure] = grouped[q.procedure] || []).push(q);
  });

  return (
    <div className="glass-strong" style={{ borderRadius: 20, padding: '36px', maxWidth: 720, margin: '0 auto', textAlign: 'left' }}>
      {/* Score header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 24, marginBottom: 24, paddingBottom: 24, borderBottom: '1px solid rgba(250,250,248,0.08)', flexWrap: 'wrap' }}>
        <div style={{ flex: '0 0 auto' }}>
          <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'rgba(250,250,248,0.5)', marginBottom: 8 }}>Visibility Score · {result.label}</div>
          <div style={{ fontFamily: "'SF Pro Display','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 72, fontWeight: 800, fontStyle: 'italic', color: scoreColor, lineHeight: 1, letterSpacing: '-0.04em' }}>
            {score}<span style={{ fontSize: 28, color: 'rgba(250,250,248,0.4)' }}>/100</span>
          </div>
          <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'rgba(250,250,248,0.4)', marginTop: 8 }}>
            {result.matches} of {result.total} queries cited you
          </div>
        </div>
        <div style={{ flex: 1, minWidth: 240 }}>
          <div style={{ fontFamily: "'SF Pro Display','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 22, fontStyle: 'italic', color: '#FAFAF8', lineHeight: 1.3, letterSpacing: '-0.02em' }}>
            {result.headline}
          </div>
          <div style={{ fontFamily: "'SF Pro Text','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 13, color: 'rgba(250,250,248,0.5)', marginTop: 8 }}>
            {result.practice}{result.surgeon ? ` · ${result.surgeon}` : ''} · {result.zip}
          </div>
          {result.leadEmail && (
            <div style={{ fontFamily: "'SF Pro Text','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 13, color: 'rgba(250,250,248,0.5)', marginTop: 6 }}>
              We've also sent the full report to {result.leadEmail}
            </div>
          )}
        </div>
      </div>

      {/* Per-procedure breakdown */}
      <div style={{ display: 'grid', gap: 22, marginBottom: 28 }}>
        {Object.entries(grouped).map(([proc, queries]) => {
          const pMatches = queries.filter(q => q.matched).length;
          return (
            <div key={proc}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12 }}>
                <div style={{ fontFamily: "'SF Pro Display','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 18, fontStyle: 'italic', color: '#FAFAF8', letterSpacing: '-0.01em' }}>{proc}</div>
                <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', color: pMatches > 0 ? gold : 'rgba(250,250,248,0.4)' }}>{pMatches}/{queries.length} cited</div>
              </div>
              <div style={{ display: 'grid', gap: 10 }}>
                {queries.map((q, i) => (
                  <div key={i} style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: 14, padding: '16px 18px', background: q.matched ? 'rgba(201,168,76,0.06)' : 'rgba(255,255,255,0.025)', borderRadius: 10, alignItems: 'start', border: q.matched ? `1px solid rgba(201,168,76,0.2)` : '1px solid rgba(255,255,255,0.04)' }}>
                    <span style={{ width: 22, height: 22, borderRadius: '50%', background: q.matched ? 'rgba(0,200,120,0.15)' : 'rgba(224,122,95,0.15)', color: q.matched ? '#3DD68C' : '#E07A5F', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 600, marginTop: 2 }}>
                      {q.matched ? '✓' : '✕'}
                    </span>
                    <div>
                      <div style={{ fontFamily: "'SF Pro Text','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 13.5, color: '#FAFAF8', fontWeight: 500, marginBottom: 8, lineHeight: 1.45 }}>{q.query}</div>
                      <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 9.5, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'rgba(250,250,248,0.4)', marginBottom: 4 }}>
                        {q.matched ? 'Perplexity recommended:' : "Perplexity recommended (you weren't named):"}
                      </div>
                      <div style={{ fontFamily: "'SF Pro Text','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 12.5, color: 'rgba(250,250,248,0.7)', lineHeight: 1.6, whiteSpace: 'pre-wrap' }}>
                        {q.response || '(no response)'}
                      </div>
                      {q.citations && q.citations.length > 0 && (
                        <div style={{ marginTop: 10, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                          {q.citations.slice(0, 6).map((url, ci) => {
                            let host = url;
                            try { host = new URL(url).hostname.replace(/^www\./, ''); } catch(e) {}
                            return (
                              <a key={ci} href={url} target="_blank" rel="noopener noreferrer" style={{
                                fontFamily: "'JetBrains Mono',monospace", fontSize: 10, letterSpacing: '0.05em',
                                color: 'rgba(201,168,76,0.85)', textDecoration: 'none',
                                padding: '3px 8px', borderRadius: 6,
                                background: 'rgba(201,168,76,0.08)', border: '1px solid rgba(201,168,76,0.18)',
                              }}>↗ {host}</a>
                            );
                          })}
                        </div>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          );
        })}
      </div>

      {/* Disclaimer */}
      <div style={{ fontFamily: "'SF Pro Text','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 11.5, color: 'rgba(250,250,248,0.4)', lineHeight: 1.6, marginBottom: 24, padding: '14px 16px', background: 'rgba(255,255,255,0.02)', borderRadius: 10, borderLeft: `2px solid rgba(250,250,248,0.15)` }}>
        This live check runs on Perplexity. Your full Citation Gap Report tests all four major AI engines — ChatGPT, Gemini, Grok, and Google AI Overviews — across 50 queries (200 data points) for a defensible citation rate.
      </div>

      {/* Email capture */}
      <div style={{ background: 'rgba(195,159,80,0.06)', borderRadius: 14, padding: '24px 24px', border: `1px solid rgba(201,168,76,0.2)` }}>
        <div style={{ fontFamily: "'SF Pro Display','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 18, fontStyle: 'italic', color: '#FAFAF8', marginBottom: 6, letterSpacing: '-0.01em' }}>
          Get the full 50-query Citation Gap Report
        </div>
        <div style={{ fontFamily: "'SF Pro Text','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 13, color: 'rgba(250,250,248,0.6)', marginBottom: 16, lineHeight: 1.6 }}>
          Across all 5 AI engines (ChatGPT, Gemini, Grok, Google AI Overviews, and Perplexity). Free. Delivered in 7 days.
        </div>
        <form onSubmit={handleClaim} style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 10 }}>
          <input type="email" required placeholder="your@practice.com" value={email} onChange={e => setEmail(e.target.value)}
            style={{ fontFamily: "'SF Pro Text','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 14, color: '#FAFAF8', background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(250,250,248,0.15)', borderRadius: 10, padding: '12px 16px', outline: 'none' }} />
          <button type="submit" className="btn-gold"><span>Claim Report</span></button>
        </form>
        {emailErr && <div style={{ fontFamily: "'SF Pro Text','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 12, color: '#E07A5F', marginTop: 8 }}>{emailErr}</div>}
      </div>

      <button onClick={reset} style={{ marginTop: 20, background: 'none', border: 'none', cursor: 'pointer', fontFamily: "'SF Pro Text','-apple-system',BlinkMacSystemFont,sans-serif", fontSize: 12, color: 'rgba(250,250,248,0.5)', textDecoration: 'underline', display: 'block', marginInline: 'auto' }}>
        Run another check
      </button>
    </div>
  );
}

window.InstantVisibilityCheck = InstantVisibilityCheck;
