/* ============================================================
   Bizia — Client Review Page (/client/review/:token)
   Public, no auth, no admin sidebar.
   ============================================================ */
(function () {
  const { useState, useEffect, useRef } = React;
  const e = React.createElement;

  const VIEWPORTS = [
    { id: 'desktop', label: 'Desktop', width: 1440 },
    { id: 'laptop',  label: 'Laptop',  width: 1280 },
    { id: 'tablet',  label: 'Tablet',  width: 768  },
    { id: 'mobile',  label: 'Mobile',  width: 390  },
  ];

  function VpBtn({ vp, active, onClick }) {
    const [hov, setHov] = useState(false);
    return e('button', {
      onClick,
      onMouseEnter: () => setHov(true),
      onMouseLeave: () => setHov(false),
      style: {
        height: 34, padding: '0 12px', border: 'none', borderRadius: 8, cursor: 'pointer',
        fontSize: 13, fontWeight: 500,
        background: active ? '#5B5CFF' : hov ? '#f0f0f5' : 'transparent',
        color: active ? '#fff' : '#555',
        transition: 'background .15s',
      },
    }, vp.label);
  }

  function ClientReviewPage({ path }) {
    const token = (path || '').split('/')[3];
    const [info, setInfo] = useState(null);
    const [error, setError] = useState(null);
    const [viewport, setViewport] = useState('desktop');
    const [comment, setComment] = useState('');
    const [submitting, setSubmitting] = useState(false);
    const [approved, setApproved] = useState(false);
    const [commented, setCommented] = useState(false);
    const [approving, setApproving] = useState(false);
    const [approveError, setApproveError] = useState('');
    const iframeRef = useRef(null);

    useEffect(() => {
      if (!token) { setError('No review token provided.'); return; }
      window.API.publicReview.get(token).then(r => {
        const data = r?.data || r;
        setInfo(data);
      }).catch(() => setError('This review link is invalid or has expired.'));
    }, [token]);

    const vpWidth = VIEWPORTS.find(v => v.id === viewport)?.width || 1440;
    const previewUrl = info
      ? `${info.previewUrl.split('?')[0]}?reviewToken=${encodeURIComponent(token)}`
      : null;

    async function submitComment() {
      if (!comment.trim()) return;
      setSubmitting(true);
      try {
        await window.API.publicReview.comment(token, {
          pagePath: 'index.html',
          viewport,
          comment: comment.trim(),
        });
        setComment('');
        setCommented(true);
      } finally {
        setSubmitting(false);
      }
    }

    async function approveWebsite() {
      setApproving(true); setApproveError('');
      try {
        await window.API.publicReview.approve(token, { approvedBy: 'client' });
        setApproved(true);
      } catch (e) {
        setApproveError(e.message || 'Could not approve the website. Please try again.');
      } finally {
        setApproving(false);
      }
    }

    if (error) return e('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100vh', fontFamily: 'system-ui', flexDirection: 'column', gap: 16 } },
      e('div', { style: { fontSize: 40 } }, '🔒'),
      e('h2', { style: { margin: 0, color: '#333' } }, 'Link unavailable'),
      e('p', { style: { margin: 0, color: '#777' } }, error),
    );

    if (!info) return e('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100vh' } },
      e('p', { style: { color: '#777', fontFamily: 'system-ui' } }, 'Loading review…'),
    );

    if (approved) return e('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100vh', fontFamily: 'system-ui', flexDirection: 'column', gap: 16 } },
      e('div', { style: { fontSize: 48 } }, '✅'),
      e('h2', { style: { margin: 0, color: '#333' } }, 'Website approved!'),
      e('p', { style: { margin: 0, color: '#777' } }, 'Thank you. Your approval has been recorded.'),
    );

    return e('div', { style: { display: 'flex', flexDirection: 'column', height: '100vh', fontFamily: 'system-ui', background: '#f5f5f7' } },
      /* header */
      e('div', { style: { display: 'flex', alignItems: 'center', gap: 12, padding: '0 20px', height: 56, background: '#fff', borderBottom: '1px solid #e5e5e5', flexShrink: 0 } },
        e('div', { style: { width: 28, height: 28, borderRadius: 8, background: '#5B5CFF', display: 'flex', alignItems: 'center', justifyContent: 'center' } },
          e('span', { style: { color: '#fff', fontWeight: 800, fontSize: 13 } }, 'B'),
        ),
        e('div', null,
          e('p', { style: { margin: 0, fontSize: 14, fontWeight: 700, color: '#111' } }, 'Review: ' + (info.projectName || 'Your website')),
          e('p', { style: { margin: 0, fontSize: 12, color: '#999' } }, 'Please review and approve your site'),
        ),
        e('div', { style: { flex: 1 } }),
        ...VIEWPORTS.map(v => e(VpBtn, { key: v.id, vp: v, active: viewport === v.id, onClick: () => setViewport(v.id) })),
      ),

      /* main area */
      e('div', { style: { display: 'flex', flex: 1, overflow: 'hidden' } },
        /* iframe */
        e('div', { style: { flex: 1, overflow: 'auto', display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: 20 } },
          e('div', { style: { width: vpWidth, boxShadow: '0 4px 40px rgba(0,0,0,0.15)', borderRadius: 8, overflow: 'hidden', background: '#fff', flexShrink: 0, transition: 'width .2s' } },
            e('iframe', {
              ref: iframeRef,
              src: previewUrl,
              style: { width: vpWidth, height: 820, border: 'none', display: 'block' },
              title: 'Site preview',
            }),
          ),
        ),

        /* comment + approve panel */
        e('div', { style: { width: 300, background: '#fff', borderLeft: '1px solid #e5e5e5', display: 'flex', flexDirection: 'column', padding: 20, gap: 16, overflowY: 'auto', flexShrink: 0 } },
          e('h3', { style: { margin: 0, fontSize: 15, fontWeight: 700, color: '#111' } }, 'Your feedback'),

          commented && e('div', { style: { background: '#f0fdf4', border: '1px solid #86efac', borderRadius: 8, padding: '10px 12px', fontSize: 13, color: '#166534' } }, 'Comment sent! Thank you.'),

          e('textarea', {
            value: comment,
            onChange: ev => setComment(ev.target.value),
            placeholder: 'Add a comment or request a change…',
            rows: 5,
            style: { width: '100%', border: '1px solid #e5e5e5', borderRadius: 8, padding: '10px 12px', fontSize: 13, fontFamily: 'system-ui', resize: 'vertical', boxSizing: 'border-box', outline: 'none' },
          }),
          e('button', {
            onClick: submitComment,
            disabled: submitting || !comment.trim(),
            style: {
              height: 38, borderRadius: 8, border: 'none', cursor: 'pointer',
              background: '#5B5CFF', color: '#fff', fontSize: 14, fontWeight: 600,
              opacity: (!comment.trim() || submitting) ? 0.5 : 1,
            },
          }, submitting ? 'Sending…' : 'Send comment'),

          e('hr', { style: { border: 'none', borderTop: '1px solid #e5e5e5', margin: '4px 0' } }),

          e('div', { style: { background: '#f0fdf4', borderRadius: 10, padding: '14px 14px', display: 'flex', flexDirection: 'column', gap: 8 } },
            e('p', { style: { margin: 0, fontSize: 13, fontWeight: 600, color: '#111' } }, 'Ready to approve?'),
            e('p', { style: { margin: 0, fontSize: 12, color: '#555' } }, 'Approving confirms you are satisfied with the design and authorises the team to proceed.'),
            e('button', {
              onClick: approveWebsite,
              disabled: approving,
              style: {
                height: 40, borderRadius: 8, border: 'none', cursor: 'pointer',
                background: '#16a34a', color: '#fff', fontSize: 14, fontWeight: 600,
                opacity: approving ? 0.6 : 1,
              },
            }, approving ? 'Approving…' : '✓ Approve website'),
            approveError && e('p', { style: { margin: 0, fontSize: 12, color: '#b91c1c' } }, approveError),
          ),
        ),
      ),
    );
  }

  window.ClientReviewPage = ClientReviewPage;
})();
