// ScanStatusPage — live order status at /managed-scan/status/?id=<submissionId>.
// Polls /api/managed-scan-status every 10s; each poll also advances the order
// server-side (domain verification attempts, enqueue retries).

function ScanStatusPage() {
  const { React } = window;
  const { useState, useEffect } = React;

  const submissionId = new URLSearchParams(window.location.search).get('id');

  const [order, setOrder] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!submissionId) return undefined;
    let cancelled = false;

    async function poll() {
      try {
        const res = await fetch(`/api/managed-scan-status?id=${encodeURIComponent(submissionId)}`);
        const json = await res.json().catch(() => ({}));
        if (cancelled) return;
        if (!res.ok || !json.ok) {
          setError(json.error || 'order not found');
          return;
        }
        setError(null);
        setOrder(json);
      } catch {
        if (!cancelled) setError('network error — retrying…');
      }
    }

    poll();
    const interval = setInterval(poll, 10000);
    return () => {
      cancelled = true;
      clearInterval(interval);
    };
  }, [submissionId]);

  const STATUS_COPY = {
    pending_payment: {
      title: 'waiting for payment',
      body: 'your payment has not completed yet. if you closed the checkout window, start again from the managed scan page.',
    },
    paid: {
      title: 'payment received',
      body: 'your scan is being queued — this page updates automatically.',
    },
    paid_pending_verification: {
      title: 'verify your domain',
      body: 'payment received. prove you control the target domain and the scan starts automatically — we re-check every time this page refreshes.',
    },
    queued: {
      title: 'scan queued',
      body: 'your scan is queued and will start shortly. you can close this page — your report link arrives by email.',
    },
    running: {
      title: 'scan running',
      body: 'sekura is scanning now. depending on the size of the target this takes from minutes to a few hours. your report link arrives by email.',
    },
    delivered: {
      title: 'report ready',
      body: 'your scan is complete. download links are below and in your email.',
    },
    failed: {
      title: 'scan failed',
      body: 'something went wrong and we could not complete your scan.',
    },
    refunded: {
      title: 'refunded',
      body: 'we could not complete your scan, so we refunded your payment in full (allow 5–10 business days). reply to your confirmation email if you want us to investigate or retry.',
    },
  };

  function renderVerification() {
    if (!order || order.status !== 'paid_pending_verification' || !order.verificationToken) return null;
    let host = order.liveUrl;
    let origin = order.liveUrl;
    try {
      host = new URL(order.liveUrl).hostname;
      origin = new URL(order.liveUrl).origin;
    } catch {}

    return (
      <div className="review-section">
        <div className="review-section-header">
          <span className="review-section-title">verification — pick either option</span>
        </div>
        <div className="success-summary">
          <div className="summary-row">
            <span className="summary-key">option 1 — DNS TXT</span>
            <span className="summary-val" style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: '12px' }}>
              _sekura-verify.{host} → "sekura-verify={order.verificationToken}"
            </span>
          </div>
          <div className="summary-row">
            <span className="summary-key">option 2 — file</span>
            <span className="summary-val" style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: '12px' }}>
              {origin}/.well-known/sekura-verify.txt containing sekura-verify={order.verificationToken}
            </span>
          </div>
        </div>
        <p style={{ fontSize: '12px', color: 'var(--muted)', marginTop: '12px' }}>
          unverified orders are automatically refunded after 72 hours.
        </p>
      </div>
    );
  }

  function renderReports() {
    if (!order || order.status !== 'delivered' || !order.downloadToken) return null;
    const base = `/api/scan-report?token=${order.downloadToken}`;
    return (
      <div className="review-section">
        <div className="review-section-header">
          <span className="review-section-title">your report</span>
        </div>
        <div className="success-summary">
          {order.findingsCount != null && (
            <div className="summary-row">
              <span className="summary-key">findings</span>
              <span className="summary-val">{order.findingsCount}</span>
            </div>
          )}
          <div className="summary-row">
            <span className="summary-key">interactive report</span>
            <span className="summary-val"><a href={base} target="_blank" rel="noopener noreferrer">open report.html →</a></span>
          </div>
          {(order.reportFiles || []).filter(f => f !== 'report.html').map(f => (
            <div className="summary-row" key={f}>
              <span className="summary-key">{f}</span>
              <span className="summary-val"><a href={`${base}&file=${f}`}>download</a></span>
            </div>
          ))}
        </div>
        <p style={{ fontSize: '12px', color: 'var(--muted)', marginTop: '12px' }}>
          links expire in 30 days — save what you need.
        </p>
      </div>
    );
  }

  const copy = order ? (STATUS_COPY[order.status] || { title: order.status, body: '' }) : null;
  const spinning = order && ['paid', 'queued', 'running', 'paid_pending_verification'].includes(order.status);

  return (
    <React.Fragment>
      <div className="intake-page">
        <div className="intake-inner">
          <h1 className="intake-title">scan status</h1>

          {!submissionId && (
            <p className="intake-sub">missing order id — use the link from your confirmation email.</p>
          )}

          {error && <div className="submit-error">{error}</div>}

          {order && copy && (
            <React.Fragment>
              <p className="intake-sub">
                {spinning && <span className="si-circle" style={{ display: 'inline-block', marginRight: '8px' }}>…</span>}
                <strong>{copy.title}</strong> — {copy.body}
              </p>

              <div className="review-section">
                <div className="success-summary">
                  <div className="summary-row"><span className="summary-key">order</span><span className="summary-val">{order.submissionId}</span></div>
                  <div className="summary-row"><span className="summary-key">scan type</span><span className="summary-val">{order.scanType}</span></div>
                  {order.repoUrl && <div className="summary-row"><span className="summary-key">repository</span><span className="summary-val">{order.repoUrl}</span></div>}
                  {order.liveUrl && <div className="summary-row"><span className="summary-key">live URL</span><span className="summary-val">{order.liveUrl}</span></div>}
                  <div className="summary-row"><span className="summary-key">status</span><span className="summary-val">{order.status}</span></div>
                  {order.failureReason && (
                    <div className="summary-row"><span className="summary-key">reason</span><span className="summary-val">{order.failureReason}</span></div>
                  )}
                </div>
              </div>

              {renderVerification()}
              {renderReports()}
            </React.Fragment>
          )}

          {!order && !error && submissionId && (
            <p className="intake-sub">loading…</p>
          )}
        </div>
      </div>

    </React.Fragment>
  );
}

window.ScanStatusPage = ScanStatusPage;
