// agreement.jsx — Song Submission Agreement gate.
// Shown BEFORE a user can upload any audio for evaluation (feed peer-rating
// OR paid coach review). The user must view the agreement PDF and tick
// "I have read and agree"; the acceptance is persisted to Supabase via
// window.LAUNCH_USER.acceptSongAgreement (see user.jsx / song-agreement.sql).
//
// Reusable across screens — render inline when an upload is attempted without
// consent:  window.LAUNCH_AGREEMENT.SongAgreementGate({ theme, onClose, onAccepted })

const { useState: useStateAgr } = React;
const { DisplayHeading: DisplayHeadingAgr } = window.LAUNCH_SCREENS_1;

function SongAgreementGate({ theme, onClose, onAccepted }) {
  const U = window.LAUNCH_USER;
  const url = (U && U.songAgreementUrl) ? U.songAgreementUrl() : 'documents/Song_Submission_Agreement_Launch.pdf';
  const version = (U && U.songAgreementVersion) ? U.songAgreementVersion() : '';

  const [opened, setOpened] = useStateAgr(false);   // did they open/scroll the doc?
  const [checked, setChecked] = useStateAgr(false);  // ticked "I agree"
  const [busy, setBusy] = useStateAgr(false);
  const [err, setErr] = useStateAgr(null);

  const canAgree = opened && checked && !busy;

  const confirm = async () => {
    if (!canAgree) return;
    setBusy(true); setErr(null);
    const res = U && U.acceptSongAgreement ? await U.acceptSongAgreement() : { error: 'Unavailable' };
    setBusy(false);
    if (res && res.ok) { onAccepted && onAccepted(); }
    else { setErr((res && res.error) || 'Could not save your agreement. Try again.'); }
  };

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 120,
      background: theme.bg, display: 'flex', flexDirection: 'column',
      animation: 'agrUp .22s cubic-bezier(.2,.8,.2,1)',
    }}>
      <style>{`@keyframes agrUp { from { transform: translateY(100%); } to { transform: translateY(0); } }`}</style>

      {/* Top bar */}
      <div style={{
        paddingTop: 58, paddingBottom: 8, paddingLeft: theme.pad, paddingRight: theme.pad,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        borderBottom: `1px solid ${theme.border}`, flexShrink: 0,
      }}>
        <button onClick={onClose} style={{
          width: 38, height: 38, borderRadius: 12,
          background: theme.surface, border: `1px solid ${theme.border}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer', padding: 0,
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M2 2l10 10M12 2L2 12" stroke={theme.text} strokeWidth="2.2" strokeLinecap="round"/>
          </svg>
        </button>
        <div style={{
          fontFamily: theme.fontMono, fontSize: 10, color: theme.muted,
          letterSpacing: 1, fontWeight: 700,
        }}>REQUIRED · STEP 1</div>
      </div>

      {/* Heading */}
      <div style={{ padding: `${theme.gap}px ${theme.pad}px 10px`, flexShrink: 0 }}>
        <div style={{ fontFamily: theme.fontMono, fontSize: 10, color: theme.accent, letterSpacing: 1, fontWeight: 700 }}>
          ★ BEFORE YOU UPLOAD
        </div>
        <DisplayHeadingAgr theme={theme} size={28} style={{ marginTop: 4 }}>
          SONG SUBMISSION<br/>AGREEMENT
        </DisplayHeadingAgr>
        <div style={{
          fontFamily: theme.fontBody, fontSize: 13, color: theme.muted,
          marginTop: 8, lineHeight: 1.5,
        }}>
          Please read how your audio will be handled. You must agree before submitting any track for evaluation.
        </div>
      </div>

      {/* PDF viewer */}
      <div style={{
        flex: 1, minHeight: 0, margin: `0 ${theme.pad}px`,
        borderRadius: 14, overflow: 'hidden',
        border: `1px solid ${theme.border}`, background: theme.surface,
        position: 'relative',
      }}>
        <iframe
          title="Song Submission Agreement"
          src={url + '#view=FitH'}
          onLoad={() => setOpened(true)}
          style={{ width: '100%', height: '100%', border: 'none', background: '#fff' }}
        />
      </div>

      {/* Open-in-new fallback (PDF doesn't render inline on some mobile webviews) */}
      <div style={{ padding: `8px ${theme.pad}px 0`, flexShrink: 0 }}>
        <a
          href={url}
          target="_blank"
          rel="noreferrer"
          onClick={() => setOpened(true)}
          style={{
            fontFamily: theme.fontMono, fontSize: 11, color: theme.accent,
            letterSpacing: 0.5, fontWeight: 700, textDecoration: 'none',
          }}>↗ OPEN / DOWNLOAD THE FULL DOCUMENT</a>
      </div>

      {/* Consent + confirm */}
      <div style={{
        padding: `12px ${theme.pad}px 28px`,
        borderTop: `1px solid ${theme.border}`, background: theme.bg,
        flexShrink: 0,
      }}>
        <button
          onClick={() => setChecked(c => !c)}
          style={{
            width: '100%', display: 'flex', alignItems: 'flex-start', gap: 12,
            background: 'transparent', border: 'none', cursor: 'pointer',
            textAlign: 'left', padding: '4px 0 12px',
          }}>
          <div style={{
            width: 24, height: 24, borderRadius: 7, flexShrink: 0, marginTop: 1,
            background: checked ? theme.accent : 'transparent',
            border: `2px solid ${checked ? theme.accent : theme.border}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            transition: 'background .15s, border-color .15s',
          }}>
            {checked &&
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                <path d="M5 12l5 5L20 6" stroke={theme.onAccent} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>}
          </div>
          <span style={{ fontFamily: theme.fontBody, fontSize: 13, color: theme.text, lineHeight: 1.45, fontWeight: 600 }}>
            I have read and agree to the Song Submission Agreement, including how my uploaded audio will be stored, shared and reviewed.
          </span>
        </button>

        {err &&
          <div style={{
            marginBottom: 10, padding: '9px 12px', borderRadius: 10,
            background: theme.surface2, border: `1px solid ${theme.border}`,
            fontFamily: theme.fontBody, fontSize: 12, color: theme.accent,
          }}>{err}</div>
        }

        <button
          onClick={confirm}
          disabled={!canAgree}
          style={{
            width: '100%', padding: '15px 18px', borderRadius: 12, border: 'none',
            background: canAgree ? theme.accent : theme.surface2,
            color: canAgree ? theme.onAccent : theme.faint,
            cursor: canAgree ? 'pointer' : 'not-allowed',
            fontFamily: theme.fontDisplay, fontSize: 15, letterSpacing: 1,
            textTransform: 'uppercase',
          }}>
          {busy ? 'SAVING…' : (!opened ? 'OPEN THE DOCUMENT FIRST' : !checked ? 'TICK THE BOX TO CONTINUE' : 'I AGREE · CONTINUE →')}
        </button>
        {version &&
          <div style={{
            fontFamily: theme.fontMono, fontSize: 9, color: theme.faint,
            letterSpacing: 0.8, fontWeight: 600, textAlign: 'center', marginTop: 8,
          }}>AGREEMENT VERSION · {version.toUpperCase()}</div>
        }
      </div>
    </div>
  );
}

window.LAUNCH_AGREEMENT = { SongAgreementGate };
