/* ============================================================
   Bizia — Responsive Preview Page (/app/preview/:projectId)
   Full-bleed; no AppShell.
   ============================================================ */
(function () {
  const { useState, useEffect, useRef, useCallback } = React;
  const e = React.createElement;

  const VIEWPORTS = [
    { id: 'desktop',  label: 'Desktop',  width: 1440, icon: 'monitor' },
    { id: 'laptop',   label: 'Laptop',   width: 1280, icon: 'laptop' },
    { id: 'tablet',   label: 'Tablet',   width: 768,  icon: 'tablet' },
    { id: 'mobile',   label: 'Mobile',   width: 390,  icon: 'smartphone' },
  ];
  const ZOOMS = [50, 75, 100];

  /* ---- Toolbar button ---- */
  function ToolBtn({ icon, label, active, onClick, danger }) {
    const [hov, setHov] = useState(false);
    return e('button', {
      title: label,
      onClick,
      onMouseEnter: () => setHov(true),
      onMouseLeave: () => setHov(false),
      style: {
        display: 'flex', alignItems: 'center', gap: 6,
        height: 34, padding: '0 10px', borderRadius: 8, border: 'none', cursor: 'pointer',
        fontSize: 13, fontWeight: 500,
        background: active ? 'var(--primary-soft)' : hov ? 'var(--surface-3)' : 'transparent',
        color: active ? 'var(--primary-700)' : danger ? 'var(--danger)' : 'var(--text-2)',
        transition: 'background .15s',
      },
    },
      e(window.Icon, { name: icon, size: 15 }),
      label && e('span', null, label),
    );
  }

  /* ---- Share modal ---- */
  function ShareModal({ projectId, onClose }) {
    const [links, setLinks] = useState([]);
    const [creating, setCreating] = useState(false);
    const [newUrl, setNewUrl] = useState(null);
    const [copied, setCopied] = useState(false);
    const [error, setError] = useState('');

    useEffect(() => {
      window.API.reviewLinks.list(projectId).then(r => setLinks(Array.isArray(r) ? r : (r?.data || [])));
    }, [projectId]);

    async function createLink() {
      setCreating(true); setError('');
      try {
        const r = await window.API.reviewLinks.create(projectId, {});
        const data = r?.data || r;
        setNewUrl(data.reviewUrl);
        setLinks(prev => [data, ...prev]);
      } catch (e) {
        setError(e.message || 'Could not create review link.');
      } finally {
        setCreating(false);
      }
    }

    async function revokeLink(id) {
      setError('');
      try {
        await window.API.reviewLinks.revoke(projectId, id);
        setLinks(prev => prev.map(l => l.id === id ? { ...l, status: 'revoked' } : l));
      } catch (e) {
        setError(e.message || 'Could not revoke review link.');
      }
    }

    function copy(url) {
      navigator.clipboard.writeText(url).then(() => { setCopied(true); setTimeout(() => setCopied(false), 2000); });
    }

    return e('div', {
      style: {
        position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', zIndex: 1000,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      },
      onClick: onClose,
    },
      e('div', {
        onClick: ev => ev.stopPropagation(),
        style: {
          background: 'var(--surface)', borderRadius: 16, padding: 28, width: 480, maxWidth: '94vw',
          boxShadow: 'var(--sh-xl)', display: 'flex', flexDirection: 'column', gap: 16,
        },
      },
        e('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between' } },
          e('h3', { style: { margin: 0, fontSize: 16, fontWeight: 700 } }, 'Share with client'),
          e(ToolBtn, { icon: 'x', onClick: onClose }),
        ),
        error && e('div', { style: { background: 'var(--danger-soft)', color: 'var(--danger)', borderRadius: 10, padding: '10px 12px', fontSize: 13 } }, error),
        newUrl && e('div', { style: { background: 'var(--success-soft)', borderRadius: 10, padding: '10px 12px', display: 'flex', alignItems: 'center', gap: 8 } },
          e('span', { style: { flex: 1, fontSize: 13, wordBreak: 'break-all' } }, newUrl),
          e(window.Button, { size: 'sm', variant: 'outline', icon: copied ? 'check' : 'copy', onClick: () => copy(newUrl) }, copied ? 'Copied' : 'Copy'),
        ),
        e(window.Button, { full: true, icon: 'link', onClick: createLink, disabled: creating }, creating ? 'Creating…' : 'Create review link'),
        links.length > 0 && e('div', { style: { display: 'flex', flexDirection: 'column', gap: 6 } },
          e('p', { style: { margin: 0, fontSize: 12, color: 'var(--text-3)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.05em' } }, 'Existing links'),
          ...links.map(l => e('div', { key: l.id, style: { display: 'flex', alignItems: 'center', gap: 8, padding: '8px 10px', borderRadius: 8, background: 'var(--surface-2)' } },
            e(window.Icon, { name: l.status === 'active' ? 'link' : 'link-2-off', size: 14 }),
            e('span', { style: { flex: 1, fontSize: 12, color: l.status === 'active' ? 'var(--text)' : 'var(--text-3)' } }, l.id.slice(0, 12) + '… · ' + l.status),
            l.status === 'active' && e(window.Button, { size: 'sm', variant: 'danger', onClick: () => revokeLink(l.id) }, 'Revoke'),
          )),
        ),
      ),
    );
  }

  /* ---- Comments sidebar ---- */
  function CommentsSidebar({ projectId, linkId, currentPage }) {
    const [comments, setComments] = useState([]);

    useEffect(() => {
      if (!linkId) return;
      window.API.reviewLinks.comments(projectId, linkId)
        .then(r => setComments(Array.isArray(r) ? r : (r?.data || [])));
    }, [projectId, linkId, currentPage]);

    const filtered = currentPage ? comments.filter(c => c.pagePath === currentPage) : comments;

    async function resolve(c) {
      await window.API.reviewLinks.resolveComment(projectId, linkId, c.id, 'resolved');
      setComments(prev => prev.map(x => x.id === c.id ? { ...x, status: 'resolved' } : x));
    }

    return e('div', { style: { display: 'flex', flexDirection: 'column', gap: 8, height: '100%', overflowY: 'auto', padding: 12 } },
      e('p', { style: { margin: 0, fontSize: 12, fontWeight: 700, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.05em' } }, 'Client Comments'),
      filtered.length === 0
        ? e('p', { style: { fontSize: 13, color: 'var(--text-3)', textAlign: 'center', marginTop: 24 } }, 'No comments yet')
        : filtered.map(c => e('div', { key: c.id, style: { background: 'var(--surface-2)', borderRadius: 10, padding: '10px 12px', display: 'flex', flexDirection: 'column', gap: 6, opacity: c.status === 'resolved' ? 0.55 : 1 } },
            e('p', { style: { margin: 0, fontSize: 13 } }, c.comment),
            e('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
              e('span', { style: { fontSize: 11, color: 'var(--text-3)' } }, c.viewport + ' · ' + c.pagePath),
              c.status !== 'resolved' && e(window.Button, { size: 'sm', variant: 'outline', onClick: () => resolve(c) }, 'Resolve'),
            ),
          )),
    );
  }

  /* ---- Main PreviewPage ---- */
  function PreviewPage({ path }) {
    const projectId = (path || '').split('/')[3];
    const [manifest, setManifest] = useState(null);
    const [viewport, setViewport] = useState('desktop');
    const [zoom, setZoom] = useState(100);
    const [activePage, setActivePage] = useState(null);
    const [loading, setLoading] = useState(true);
    const [showShare, setShowShare] = useState(false);
    const [showComments, setShowComments] = useState(false);
    const [latestLinkId, setLatestLinkId] = useState(null);
    const iframeRef = useRef(null);

    const vpWidth = VIEWPORTS.find(v => v.id === viewport)?.width || 1440;

    function loadManifest() {
      if (!projectId) return;
      setLoading(true);
      window.API.preview.projectManifest(projectId).then(r => {
        const data = r?.data || r;
        setManifest(data);
        if (data?.pages?.length && !activePage) setActivePage(data.pages[0].path);
        setLoading(false);
      }).catch(() => setLoading(false));
    }

    useEffect(() => { loadManifest(); }, [projectId]);

    // fetch latest link id for comments panel
    useEffect(() => {
      if (!projectId || !showComments) return;
      window.API.reviewLinks.list(projectId).then(r => {
        const arr = Array.isArray(r) ? r : (r?.data || []);
        const active = arr.find(l => l.status === 'active');
        if (active) setLatestLinkId(active.id);
      });
    }, [projectId, showComments]);

    const currentPageUrl = activePage && projectId
      ? window.API.preview.url(projectId, activePage)
      : null;

    const previewUrl = currentPageUrl;

    function openNewTab() { if (previewUrl) window.open(previewUrl, '_blank'); }
    function copyLink() { if (previewUrl) navigator.clipboard.writeText(previewUrl); }
    function refresh() { if (iframeRef.current) iframeRef.current.src = iframeRef.current.src; loadManifest(); }

    if (!projectId) return e('div', { style: { padding: 40, textAlign: 'center' } }, 'No project selected.');

    return e('div', {
      style: { display: 'flex', flexDirection: 'column', height: '100vh', background: 'var(--canvas, #F5F5F7)', fontFamily: 'var(--font)' },
    },
      /* ---- Top bar ---- */
      e('div', { style: { display: 'flex', alignItems: 'center', gap: 8, padding: '0 12px', height: 52, background: 'var(--surface)', borderBottom: '1px solid var(--border)', flexShrink: 0 } },
        e(ToolBtn, { icon: 'arrowLeft', onClick: () => window.navigate('/app') }),
        e('div', { style: { flex: 1 } }),
        /* viewport buttons */
        ...VIEWPORTS.map(v => e(ToolBtn, { key: v.id, icon: v.icon, label: v.label, active: viewport === v.id, onClick: () => setViewport(v.id) })),
        e('div', { style: { width: 1, height: 20, background: 'var(--border)', margin: '0 4px' } }),
        /* zoom */
        ...ZOOMS.map(z => e(ToolBtn, { key: z, icon: null, label: z + '%', active: zoom === z, onClick: () => setZoom(z) })),
        e('div', { style: { width: 1, height: 20, background: 'var(--border)', margin: '0 4px' } }),
        e(ToolBtn, { icon: 'refreshCw', label: 'Refresh', onClick: refresh }),
        e(ToolBtn, { icon: 'externalLink', label: 'Open', onClick: openNewTab }),
        e(ToolBtn, { icon: 'copy', label: 'Copy link', onClick: copyLink }),
        e('div', { style: { width: 1, height: 20, background: 'var(--border)', margin: '0 4px' } }),
        e(ToolBtn, { icon: 'messageSquare', label: 'Comments', active: showComments, onClick: () => setShowComments(s => !s) }),
        e(window.Button, { size: 'sm', variant: 'outline', icon: 'share2', onClick: () => setShowShare(true) }, 'Share'),
        e(window.Button, { size: 'sm', icon: 'rocket', onClick: () => window.navigate(`/app/go-live/${projectId}`) }, 'Go Live'),
      ),

      /* ---- Body: sidebar + canvas ---- */
      e('div', { style: { display: 'flex', flex: 1, overflow: 'hidden' } },

        /* page list sidebar */
        e('div', { style: { width: 200, background: 'var(--surface)', borderRight: '1px solid var(--border)', display: 'flex', flexDirection: 'column', overflowY: 'auto', flexShrink: 0 } },
          e('p', { style: { margin: '12px 12px 6px', fontSize: 11, fontWeight: 700, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.05em' } }, 'Pages'),
          loading
            ? e('div', { style: { padding: 12 } }, e(window.Skeleton, { h: 32 }))
            : manifest?.pages?.length
              ? manifest.pages.map(pg => e('button', {
                  key: pg.path,
                  onClick: () => setActivePage(pg.path),
                  style: {
                    display: 'flex', alignItems: 'center', gap: 8, width: '100%',
                    padding: '8px 12px', border: 'none', cursor: 'pointer', textAlign: 'left',
                    background: activePage === pg.path ? 'var(--primary-soft)' : 'transparent',
                    color: activePage === pg.path ? 'var(--primary-700)' : 'var(--text)',
                    fontSize: 13, fontWeight: activePage === pg.path ? 600 : 400,
                    borderRadius: 0,
                  },
                },
                  e(window.Icon, { name: pg.type === 'home' ? 'home' : pg.type === 'contact' ? 'mail' : 'file', size: 13 }),
                  pg.title,
                ))
              : e('p', { style: { padding: '12px', fontSize: 13, color: 'var(--text-3)' } }, 'No pages yet'),
        ),

        /* preview canvas */
        e('div', { style: { flex: 1, overflow: 'auto', display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: 24 } },
          loading
            ? e('div', { style: { width: '100%', maxWidth: 900 } }, e(window.Skeleton, { h: 500 }))
            : !manifest?.hasFiles
              ? e(window.EmptyState, {
                  icon: 'monitor',
                  title: 'No preview yet',
                  desc: 'Generate the website first to see a preview here.',
                  action: e(window.Button, { variant: 'outline', icon: 'arrowLeft', onClick: () => window.navigate('/app') }, 'Back'),
                })
              : e('div', {
                  style: {
                    width: vpWidth,
                    transform: `scale(${zoom / 100})`,
                    transformOrigin: 'top center',
                    flexShrink: 0,
                    boxShadow: '0 4px 40px rgba(0,0,0,0.18)',
                    borderRadius: 8,
                    overflow: 'hidden',
                    background: '#fff',
                    marginBottom: zoom < 100 ? -(vpWidth * (1 - zoom / 100)) : 0,
                  },
                },
                e('iframe', {
                  ref: iframeRef,
                  src: previewUrl || '',
                  style: { width: vpWidth, height: 820, border: 'none', display: 'block' },
                  title: 'Site preview',
                }),
              ),
        ),

        /* comments sidebar */
        showComments && e('div', { style: { width: 280, background: 'var(--surface)', borderLeft: '1px solid var(--border)', flexShrink: 0 } },
          latestLinkId
            ? e(CommentsSidebar, { projectId, linkId: latestLinkId, currentPage: activePage })
            : e('div', { style: { padding: 16 } },
                e('p', { style: { fontSize: 13, color: 'var(--text-3)' } }, 'Create a review link to view client comments.'),
                e(window.Button, { size: 'sm', full: true, onClick: () => setShowShare(true) }, 'Share with client'),
              ),
        ),
      ),

      showShare && e(ShareModal, { projectId, onClose: () => setShowShare(false) }),
    );
  }

  window.PreviewPage = PreviewPage;
})();
