// mariusson — Public CollectorProfile drawer
//
// What other users (artists, fellow collectors) see when they click on a
// collector's name — in Room comments, in their own Studio receipts as
// the buyer of a sale, anywhere a collector is referenced.
//
// Mirrors ArtistProfile in shape, but shows what a COLLECTOR has done on
// the platform: their public collection (owned works), commissions they've
// placed, and a way to reach them. It's a public face — not the editor;
// users edit their own data via the right-side UserProfileDrawer.

(() => {
  function CollectorPublicProfile({ ownerId, collector, role, visible, onClose, catalogue }) {
    // Resolve account if we only got the id (e.g. from an order)
    const account = collector || (() => {
      try {
        const users = JSON.parse(localStorage.getItem('mariusson:users') || '[]');
        return users.find((u) => u.id === ownerId) || null;
      } catch { return null; }
    })();

    const owned = window.AN_STUDIO ? window.AN_STUDIO.ownedWorksForBuyer(ownerId) : [];
    const orders = window.AN_PAY ? window.AN_PAY.listOrdersForBuyer(ownerId) : [];
    const purchases = orders.filter((o) => o.type === 'purchase');
    const commissions = orders.filter((o) => o.type === 'commission');
    const donations = orders.filter((o) => o.type === 'donate');

    const totalSpent = orders.reduce((acc, o) => acc + (o.amount || 0), 0);

    const findInCat = (id) => (catalogue || []).find((w) => w.id === id);

    const handle = '@' + (account?.handle || (account?.name || 'collector').toLowerCase().replace(/[^a-z0-9]/g, '').slice(0, 12) || 'collector');
    const displayName = account?.name || 'A collector';
    const region = account?.region || '—';
    const bio = account?.bio || 'A collector on mariusson.';

    return (
      <div data-atlas-panel onClick={onClose} style={{
        position: 'absolute', inset: 0, zIndex: 50,
        background: visible ? 'rgba(14,14,12,0.45)' : 'rgba(14,14,12,0)',
        backdropFilter: visible ? 'blur(8px)' : 'blur(0px)',
        WebkitBackdropFilter: visible ? 'blur(8px)' : 'blur(0px)',
        transition: 'background 320ms var(--ease-out), backdrop-filter 320ms var(--ease-out), -webkit-backdrop-filter 320ms var(--ease-out)',
      }}>
        <div data-atlas-drawer onClick={(e) => e.stopPropagation()} style={{
          position: 'absolute', top: 0, right: 0, bottom: 0,
          width: 'min(820px, 94%)',
          background: BAU.paper, borderLeft: `1px solid ${BAU.ink}`,
          transform: visible ? 'translateX(0)' : 'translateX(100%)',
          transition: 'transform 420ms var(--ease-out)',
          display: 'flex', flexDirection: 'column', overflow: 'hidden',
        }}>
          {/* Bauhaus stripe — yellow first, signaling collector */}
          <div style={{ display: 'flex', height: 8, flexShrink: 0, borderBottom: `1px solid ${BAU.ink}` }}>
            <div style={{ flex: 3, background: BAU.yellow }} />
            <div style={{ flex: 1, background: BAU.red }} />
            <div style={{ flex: 2, background: BAU.blue }} />
          </div>

          <div style={{ flex: 1, overflowY: 'auto' }}>
            {/* Header */}
            <div style={{ padding: '24px 32px 8px', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: 'var(--mono)', fontSize: 9.5, letterSpacing: '0.18em', color: BAU.graphite, textTransform: 'uppercase' }}>
                  Collector · {region.toUpperCase()}
                </div>
                <h1 style={{
                  fontFamily: 'var(--serif)', fontSize: 56, margin: '6px 0 0',
                  lineHeight: 0.95, letterSpacing: '-0.02em', fontWeight: 400,
                  color: BAU.ink,
                }}>
                  <span style={{ fontStyle: 'italic' }}>{displayName}</span>
                </h1>
                <div style={{ marginTop: 10, fontFamily: 'var(--mono)', fontSize: 11, color: BAU.graphite }}>
                  {handle}
                </div>
                <div style={{ marginTop: 12, fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 17, color: BAU.ink, lineHeight: 1.5, maxWidth: 560 }}>
                  {bio}
                </div>
              </div>
              <button onClick={onClose} style={{
                width: 30, height: 30, background: 'transparent', border: `1px solid ${BAU.ink}`,
                cursor: 'pointer', fontSize: 16, color: BAU.ink, lineHeight: 1, padding: 0, flexShrink: 0,
              }}>×</button>
            </div>

            {/* Stats strip */}
            <div style={{
              display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
              gap: 0, margin: '16px 32px 0',
              border: `1px solid ${BAU.rule}`,
            }}>
              <CStat label="Owned" value={owned.length} accent={BAU.blue} />
              <CStat label="Commissions" value={commissions.length} accent={BAU.red} />
              <CStat label="Donations" value={donations.length} accent={BAU.yellow} />
              <CStat label="Total spent" value={`€${totalSpent.toLocaleString()}`} accent={BAU.ink} />
            </div>

            {/* Public collection grid */}
            <div style={{ padding: '24px 32px' }}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12 }}>
                <h2 style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 22, color: BAU.ink, margin: 0 }}>
                  Public collection
                </h2>
                <span style={{ fontFamily: 'var(--mono)', fontSize: 9.5, letterSpacing: '0.16em', color: BAU.graphite, textTransform: 'uppercase' }}>
                  {owned.length} work{owned.length === 1 ? '' : 's'}
                </span>
              </div>

              {owned.length === 0 ? (
                <div style={{
                  padding: '20px 18px',
                  border: `2px dashed ${BAU.rule}`, background: BAU.paper2,
                  textAlign: 'center', color: BAU.graphite,
                  fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 14,
                }}>
                  This collector hasn't acquired any works yet.
                </div>
              ) : (
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(160px, 1fr))', gap: 12 }}>
                  {owned.map(({ order, workId, workTitle, workImage, status }) => {
                    const work = findInCat(workId);
                    return (
                      <div key={order.id} style={{
                        background: BAU.paper, border: `1px solid ${BAU.ink}`,
                        display: 'flex', flexDirection: 'column',
                      }}>
                        <div style={{ width: '100%', aspectRatio: '1', overflow: 'hidden', background: BAU.paper2 }}>
                          {workImage ? (
                            <img src={workImage} alt={workTitle || ''} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                          ) : work ? (
                            <ArtTile work={work} width={160} height={160} />
                          ) : null}
                        </div>
                        <div style={{ padding: '8px 10px' }}>
                          <div style={{
                            fontFamily: 'var(--mono)', fontSize: 8.5, letterSpacing: '0.14em',
                            color: order.type === 'commission' ? BAU.red : BAU.blue,
                            textTransform: 'uppercase',
                          }}>● {status}</div>
                          <div style={{
                            marginTop: 3, fontFamily: 'var(--serif)', fontStyle: 'italic',
                            fontSize: 12.5, color: BAU.ink, lineHeight: 1.2,
                            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                          }}>{workTitle || 'Untitled'}</div>
                          <div style={{ fontFamily: 'var(--mono)', fontSize: 9, color: BAU.graphite }}>
                            {order.artistName}
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>

            {/* Recent commissions list */}
            {commissions.length > 0 && (
              <div style={{ padding: '0 32px 24px' }}>
                <h2 style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 22, color: BAU.ink, margin: '0 0 12px' }}>
                  Recent commissions
                </h2>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {commissions.slice(0, 5).map((o) => (
                    <div key={o.id} style={{
                      padding: '10px 14px', border: `1px solid ${BAU.rule}`,
                      display: 'grid', gridTemplateColumns: '1fr auto', gap: 10, alignItems: 'center',
                    }}>
                      <div>
                        <div style={{ fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '0.14em', color: BAU.graphite, textTransform: 'uppercase' }}>
                          ● Commission · {new Date(o.createdAt).toLocaleDateString()}
                        </div>
                        <div style={{ marginTop: 3, fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 14, color: BAU.ink }}>
                          {o.workTitle ? `In the spirit of ${o.workTitle} · ` : ''}{o.artistName}
                        </div>
                      </div>
                      <div style={{ fontFamily: 'var(--mono)', fontSize: 12, color: BAU.ink, textAlign: 'right' }}>
                        €{o.amount.toLocaleString()}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  }

  function CStat({ label, value, accent }) {
    return (
      <div style={{ padding: '14px 16px', borderRight: `1px solid ${BAU.rule}`, position: 'relative' }}>
        <div style={{ position: 'absolute', top: 0, left: 0, width: 18, height: 3, background: accent }} />
        <div style={{ fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '0.18em', color: BAU.graphite, textTransform: 'uppercase' }}>{label}</div>
        <div style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 26, color: BAU.ink, marginTop: 4, lineHeight: 1 }}>{value}</div>
      </div>
    );
  }

  window.CollectorPublicProfile = CollectorPublicProfile;
})();
