// screens-share.jsx — the public page at /<username>/<outfit-slug>.
//
// Read-only, works signed out, and reads through mb_get_published_outfit() on
// the anon key. That function returns only public columns — the private
// `notes` field is not part of its return type, so it cannot appear here.

const { useState: useStateSH, useEffect: useEffectSH } = React;

function SharedOutfitScreen({ username, slug, go }) {
  const [outfit, setOutfit] = useStateSH(null);
  const [loading, setLoading] = useStateSH(true);
  const [error, setError]   = useStateSH(null);
  const [copied, setCopied] = useStateSH(false);

  useEffectSH(() => {
    let cancelled = false;
    (async () => {
      setLoading(true);
      setError(null);
      const res = await window.MBOutfits.getPublished(username, slug);
      if (cancelled) return;
      if (res.error) setError(res.error);
      else setOutfit(res.outfit || null);
      setLoading(false);
    })();
    return () => { cancelled = true; };
  }, [username, slug]);

  // A view is recorded once the outfit actually resolves — a not-found page is
  // not a view of anything.
  useEffectSH(() => {
    if (outfit && outfit.id) window.MBEvents.recordView(outfit.id);
  }, [outfit && outfit.id]);

  // Title the tab after the outfit, so a shared link reads well in history.
  useEffectSH(() => {
    if (outfit) document.title = `${outfit.title || 'Outfit'} by @${outfit.username} · modaBoard`;
    else if (!loading) document.title = 'Outfit not found · modaBoard';
    return () => { document.title = 'modaBoard — Shoppable Outfit Boards for Creators'; };
  }, [outfit, loading]);

  const items = (outfit && outfit.items) || [];
  const shareUrl = outfit ? window.MBOutfits.shareUrl(outfit.username, outfit.slug) : '';

  // Every outbound link goes through /api/go, which records the click
  // server-side before redirecting, so it survives the page unloading.
  const outbound = (item) => (outfit ? window.MBEvents.outboundUrl(outfit.id, item) : null);

  // Tapping a product on the board: always record the interaction; open the
  // retailer as well when there is somewhere to go.
  const onProductActivate = (item) => {
    if (!outfit) return;
    window.MBEvents.recordProductClick(outfit.id, item);
    const href = outbound(item);
    if (href) window.open(href, '_blank', 'noopener,noreferrer');
  };

  const copy = async () => {
    try {
      await navigator.clipboard.writeText(shareUrl);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch { /* clipboard blocked — the URL is on screen to copy by hand */ }
  };

  return (
    <div style={{ minHeight: '100vh', background: '#FAFAF7', display: 'flex', flexDirection: 'column' }}>
      {/* Minimal public chrome */}
      <header style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '18px 28px', borderBottom: '1px solid rgba(20,20,18,0.06)',
      }}>
        <button onClick={() => go({ name: 'home' })} style={{
          appearance: 'none', border: 'none', background: 'transparent', padding: 0, cursor: 'pointer',
        }}><Logo size={18}/></button>
        <button onClick={() => go({ name: 'signup' })} style={{
          appearance: 'none', border: 'none', background: '#1a1a18', color: '#FAFAF7',
          fontSize: 11, padding: '9px 16px', letterSpacing: '0.14em',
          textTransform: 'uppercase', fontWeight: 500, borderRadius: 999,
          cursor: 'pointer', fontFamily: 'inherit',
        }}>Make your own</button>
      </header>

      <main style={{ flex: 1, padding: '48px 28px 72px', maxWidth: 1080, marginInline: 'auto', width: '100%' }}>
        {loading && (
          <div style={{ padding: '80px 0', textAlign: 'center', color: '#8a8580', fontSize: 13 }}>
            Loading outfit…
          </div>
        )}

        {!loading && error && (
          <NotFoundCard
            title="Something went wrong"
            body={error}
            go={go}
          />
        )}

        {!loading && !error && !outfit && (
          <NotFoundCard
            title="Outfit not found"
            body={<>There’s no published outfit at this link. It may have been unpublished,
              renamed or removed — or the address might have a typo.</>}
            go={go}
          />
        )}

        {!loading && !error && outfit && (
          <>
            <div style={{ textAlign: 'center', marginBottom: 28 }}>
              <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#8a8580' }}>
                @{outfit.username}
              </div>
              <h1 style={{
                margin: '12px 0 0', fontSize: 'clamp(30px, 5vw, 52px)', fontWeight: 400,
                letterSpacing: '-0.03em', lineHeight: 1.05,
              }}>
                <em style={{ fontFamily: "'Instrument Serif',serif", fontStyle: 'italic' }}>
                  {outfit.title || 'Untitled outfit'}
                </em>
              </h1>
              <div style={{ marginTop: 10, fontSize: 12.5, color: '#8a8580', display: 'flex', gap: 8, justifyContent: 'center', flexWrap: 'wrap' }}>
                <span>{items.length} {items.length === 1 ? 'piece' : 'pieces'}</span>
                {outfit.mood && <><span>·</span><span>{outfit.mood}</span></>}
                {outfit.published_at && (
                  <><span>·</span><span>{new Date(outfit.published_at).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })}</span></>
                )}
              </div>
            </div>

            {/* The board. Items are clickable: tapping one records the
                interaction and, when the product has a link, sends the visitor
                to the retailer through the tracking redirect. */}
            <div style={{
              maxWidth: 640, marginInline: 'auto', position: 'relative',
              borderRadius: 16, overflow: 'hidden',
              background: '#FAFAF7', border: '1px solid rgba(20,20,18,0.08)',
            }}>
              <OutfitBoard outfit={{ items }}/>
              <div style={{ position: 'absolute', inset: 0 }}>
                {items.map((it, i) => (
                  <button
                    key={'hit_' + (it.id || i)}
                    onClick={() => onProductActivate(it)}
                    title={window.MBEvents.labelFor(it) + (it.sourceUrl ? ' — view at retailer' : '')}
                    aria-label={window.MBEvents.labelFor(it)}
                    style={{
                      position: 'absolute',
                      left: it.x + '%', top: it.y + '%',
                      width: it.w + '%', height: it.h + '%',
                      transform: `rotate(${it.rot || 0}deg)`,
                      appearance: 'none', border: 'none', background: 'transparent',
                      padding: 0, cursor: it.sourceUrl ? 'pointer' : 'default',
                    }}/>
                ))}
              </div>
            </div>

            {/* The pieces */}
            {items.length > 0 && (
              <div style={{ maxWidth: 640, marginInline: 'auto', marginTop: 28 }}>
                <div style={{ fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: '#8a8580', marginBottom: 14 }}>
                  In this outfit
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                  {items.map((it, i) => {
                    const row = (
                      <>
                        <div style={{ width: 52, height: 52, borderRadius: 8, background: '#F4F2EC', border: '1px solid rgba(20,20,18,0.05)', flexShrink: 0 }}>
                          <ProductImage item={it}/>
                        </div>
                        <div style={{ minWidth: 0, flex: 1 }}>
                          <div style={{ fontSize: 10.5, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#8a8580' }}>{it.brand || '—'}</div>
                          <div style={{ fontSize: 13.5, marginTop: 2 }}>{it.name || 'Untitled product'}</div>
                          {it.store && <div style={{ fontSize: 11, color: '#8a8580', marginTop: 2 }}>{it.store}</div>}
                        </div>
                        <div style={{ fontSize: 13.5, fontVariantNumeric: 'tabular-nums', color: '#5a5a54', flexShrink: 0 }}>
                          {it.price ? formatPrice(it.price, it.currency) : ''}
                        </div>
                      </>
                    );
                    const style = {
                      display: 'flex', gap: 14, alignItems: 'center',
                      padding: '10px 12px', borderRadius: 10,
                      background: '#fff', border: '1px solid rgba(20,20,18,0.06)',
                      textDecoration: 'none', color: 'inherit',
                    };
                    const href = outbound(it);
                    return href
                      ? <a key={it.id || i} href={href}
                           target="_blank" rel="noopener noreferrer nofollow"
                           onClick={() => window.MBEvents.recordProductClick(outfit.id, it)}
                           style={style}>{row}</a>
                      : <div key={it.id || i} style={style}>{row}</div>;
                  })}
                </div>
              </div>
            )}

            {/* Share */}
            <div style={{ maxWidth: 640, marginInline: 'auto', marginTop: 28, display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
              <code style={{
                flex: 1, minWidth: 220, fontSize: 12, fontFamily: 'ui-monospace, monospace',
                color: '#5a5a54', background: '#F2EFE7', padding: '11px 14px', borderRadius: 10,
                overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
              }}>{shareUrl}</code>
              <button onClick={copy} style={{
                appearance: 'none', border: '1px solid rgba(20,20,18,0.18)', background: 'transparent',
                color: '#1a1a18', fontSize: 11, padding: '11px 18px', letterSpacing: '0.14em',
                textTransform: 'uppercase', fontWeight: 500, borderRadius: 999,
                cursor: 'pointer', fontFamily: 'inherit', flexShrink: 0,
              }}>{copied ? 'Copied' : 'Copy link'}</button>
            </div>
          </>
        )}
      </main>
    </div>
  );
}

// The page for an address that isn't one of ours. It keeps the URL it was
// reached at — a visitor who mistyped can see what they typed — and says so
// plainly rather than quietly dropping them on the homepage.
function NotFoundScreen({ go }) {
  return (
    <div style={{ padding: '96px 28px 40px' }}>
      <NotFoundCard
        title="Page not found"
        body={<>There’s nothing at <code style={{ fontFamily: 'ui-monospace, monospace', fontSize: 13 }}>{window.location.pathname}</code>. The link may be out of date, or the page may have moved.</>}
        go={go}
      />
      <Footer/>
    </div>
  );
}

function NotFoundCard({ title, body, go }) {
  return (
    <div style={{
      maxWidth: 520, marginInline: 'auto', textAlign: 'center',
      padding: '56px 32px', borderRadius: 16,
      background: '#fff', border: '1px dashed rgba(20,20,18,0.16)',
    }}>
      <h1 style={{ margin: 0, fontSize: 28, fontWeight: 400, letterSpacing: '-0.02em' }}>{title}</h1>
      <p style={{ marginTop: 12, fontSize: 14, color: '#5a5a54', lineHeight: 1.6 }}>{body}</p>
      <div style={{ marginTop: 24, display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap' }}>
        <button onClick={() => go({ name: 'home' })} style={{
          appearance: 'none', border: 'none', background: '#1a1a18', color: '#FAFAF7',
          fontSize: 11.5, padding: '12px 20px', letterSpacing: '0.14em',
          textTransform: 'uppercase', fontWeight: 500, borderRadius: 999,
          cursor: 'pointer', fontFamily: 'inherit',
        }}>Go to modaBoard</button>
        <button onClick={() => go({ name: 'explore' })} style={{
          appearance: 'none', border: '1px solid rgba(20,20,18,0.18)', background: 'transparent',
          color: '#1a1a18', fontSize: 11.5, padding: '12px 20px', letterSpacing: '0.14em',
          textTransform: 'uppercase', fontWeight: 500, borderRadius: 999,
          cursor: 'pointer', fontFamily: 'inherit',
        }}>Explore outfits</button>
      </div>
    </div>
  );
}

Object.assign(window, { SharedOutfitScreen, NotFoundCard, NotFoundScreen });
