// screens-profile.jsx — the public creator profile at /<username>.
//
// Every signed-up account is a creator, and this is their page. It is driven
// entirely by the `profiles` row and the account's *published* outfits, read
// through mb_get_public_profile() and mb_list_profile_outfits() — both
// reachable signed out, both with return types that carry only public fields.
//
// Numbers here are counted, never invented: the only stat is how many outfits
// the creator has published. Followers and saves are absent because no such
// feature exists yet; the row is laid out so one can be added beside Outfits
// when it does.

const { useState: useStatePF, useEffect: useEffectPF } = React;

function ProfileScreen({ username, go }) {
  const [profile, setProfile] = useStatePF(null);
  const [outfits, setOutfits] = useStatePF([]);
  const [loading, setLoading] = useStatePF(true);
  const [error, setError] = useStatePF(null);
  const session = useSession();
  const myUsername = useMyUsername();
  const isMe = !!(myUsername && username && myUsername.toLowerCase() === String(username).toLowerCase());

  useEffectPF(() => {
    let cancelled = false;
    (async () => {
      setLoading(true);
      setError(null);
      const res = await window.MBProfile.getPublic(username);
      if (cancelled) return;
      if (res.error) { setError(res.error); setLoading(false); return; }
      setProfile(res.profile);
      if (!res.profile) { setOutfits([]); setLoading(false); return; }
      const list = await window.MBProfile.publishedOutfits(username);
      if (cancelled) return;
      if (list.error) setError(list.error);
      else setOutfits(list.outfits);
      setLoading(false);
    })();
    return () => { cancelled = true; };
  }, [username]);

  useEffectPF(() => {
    if (profile) document.title = `${profile.displayName || '@' + profile.username} · modaBoard`;
    else if (!loading) document.title = 'Creator not found · modaBoard';
    return () => { document.title = 'modaBoard — Shoppable Outfit Boards for Creators'; };
  }, [profile, loading]);

  const name = profile ? (profile.displayName || '@' + profile.username) : '';
  const count = profile ? (profile.publishedCount != null ? profile.publishedCount : outfits.length) : 0;

  return (
    <div style={{ minHeight: '60vh' }}>
      {loading && (
        <div style={{ padding: '96px 40px', textAlign: 'center', color: '#8a8580', fontSize: 13 }}>
          Loading profile…
        </div>
      )}

      {!loading && error && (
        <div style={{ padding: '72px 28px' }}>
          <NotFoundCard title="Something went wrong" body={error} go={go}/>
        </div>
      )}

      {!loading && !error && !profile && (
        <div style={{ padding: '72px 28px' }}>
          <NotFoundCard
            title="Creator not found"
            body={<>There’s no modaBoard creator at this address. The username may have
              changed, or the link might have a typo.</>}
            go={go}
          />
        </div>
      )}

      {!loading && !error && profile && (
        <>
          <section style={{ padding: '56px 40px 36px' }}>
            <div style={{
              maxWidth: 1100, marginInline: 'auto', display: 'flex',
              gap: 32, alignItems: 'flex-start', flexWrap: 'wrap',
            }}>
              <InitialAvatar name={name} username={profile.username} size={120} src={profile.avatarUrl}/>

              <div style={{ flex: 1, minWidth: 280 }}>
                <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#8a8580' }}>
                  @{profile.username}{profile.location ? ' · ' + profile.location : ''}
                </div>
                <h1 style={{ margin: '10px 0 0', fontSize: 'clamp(32px, 5vw, 52px)', fontWeight: 400, letterSpacing: '-0.03em' }}>
                  {name}
                </h1>

                {profile.bio && (
                  <p style={{ marginTop: 16, fontSize: 16, color: '#3a3a36', lineHeight: 1.55, maxWidth: '54ch' }}>
                    {profile.bio}
                  </p>
                )}

                <SocialLinks profile={profile}/>

                {profile.tags.length > 0 && (
                  <div style={{ marginTop: 16, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                    {profile.tags.map(t => (
                      <span key={t} style={{
                        fontSize: 11, letterSpacing: '0.04em', padding: '6px 12px',
                        borderRadius: 999, background: '#F2EFE7', color: '#3a3a36',
                      }}>{t}</span>
                    ))}
                  </div>
                )}

                {/* The one honest stat. Followers and saves would be made up. */}
                <div style={{ marginTop: 22, display: 'flex', gap: 28, fontSize: 13, color: '#5a5a54' }}>
                  <div>
                    <strong style={{ color: '#1a1a18', fontSize: 18, fontWeight: 500 }}>{count}</strong>
                    &nbsp; {count === 1 ? 'Outfit' : 'Outfits'}
                  </div>
                </div>
              </div>

              {isMe && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  <button onClick={() => go({ name: 'studio', view: 'settings' })} style={profileBtnPrimary}>
                    Edit profile
                  </button>
                  <button onClick={() => go({ name: 'myoutfits' })} style={profileBtnGhost}>
                    My outfits
                  </button>
                </div>
              )}
              {!isMe && !session && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  <button onClick={() => go({ name: 'signup' })} style={profileBtnPrimary}>
                    Make your own
                  </button>
                </div>
              )}
            </div>
          </section>

          <section style={{ padding: '0 40px', borderBottom: '1px solid rgba(20,20,18,0.06)' }}>
            <div style={{ maxWidth: 1280, marginInline: 'auto', display: 'flex', gap: 28 }}>
              <div style={{
                padding: '18px 0', fontSize: 12, letterSpacing: '0.16em', textTransform: 'uppercase',
                color: '#1a1a18', fontWeight: 500, borderBottom: '2px solid #1a1a18',
              }}>Published{count ? ` (${count})` : ''}</div>
            </div>
          </section>

          <section style={{ padding: '32px 40px 64px' }}>
            <div style={{ maxWidth: 1280, marginInline: 'auto' }}>
              {outfits.length === 0 ? (
                <div style={{
                  padding: '56px 32px', textAlign: 'center', borderRadius: 16,
                  background: '#fff', border: '1px dashed rgba(20,20,18,0.16)',
                }}>
                  <h2 style={{ margin: 0, fontSize: 22, fontWeight: 400, letterSpacing: '-0.02em' }}>
                    {isMe ? 'You haven’t published anything yet' : 'Nothing published yet'}
                  </h2>
                  <p style={{ marginTop: 10, color: '#5a5a54', fontSize: 14, lineHeight: 1.6 }}>
                    {isMe
                      ? 'Publish an outfit and it appears here, on your public page.'
                      : 'This creator hasn’t published an outfit yet. Check back soon.'}
                  </p>
                  {isMe && (
                    <button onClick={() => go({ name: 'dashboard' })} style={{ ...profileBtnPrimary, marginTop: 20 }}>
                      Create an outfit
                    </button>
                  )}
                </div>
              ) : (
                <div style={{
                  display: 'grid', gap: 24,
                  gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))',
                }}>
                  {outfits.map(o => (
                    <PublishedOutfitCard
                      key={o.id}
                      outfit={o}
                      onOpen={() => go({ name: 'share', username: profile.username, slug: o.slug })}
                    />
                  ))}
                </div>
              )}
            </div>
          </section>
        </>
      )}

      <Footer/>
    </div>
  );
}

// Instagram, TikTok and a website, each shown only when the creator gave one.
// Handles are stored bare, so the URL is built here; the website is stored as a
// full http(s) URL, which the column's own CHECK constraint enforces.
function SocialLinks({ profile }) {
  const links = [
    profile.instagram && { key: 'ig', label: 'Instagram', text: '@' + profile.instagram, href: 'https://instagram.com/' + encodeURIComponent(profile.instagram) },
    profile.tiktok && { key: 'tt', label: 'TikTok', text: '@' + profile.tiktok, href: 'https://tiktok.com/@' + encodeURIComponent(profile.tiktok) },
    profile.website && { key: 'web', label: 'Website', text: profile.website.replace(/^https?:\/\//i, '').replace(/\/$/, ''), href: profile.website },
  ].filter(Boolean);

  if (!links.length) return null;

  return (
    <div style={{ marginTop: 16, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
      {links.map(l => (
        <a key={l.key} href={l.href} target="_blank" rel="noopener noreferrer nofollow"
           title={l.label} style={{
             display: 'inline-flex', alignItems: 'center', gap: 7,
             fontSize: 12.5, color: '#1a1a18', textDecoration: 'none',
             padding: '7px 13px', borderRadius: 999,
             border: '1px solid rgba(20,20,18,0.14)', background: '#fff',
             maxWidth: 260, overflow: 'hidden',
           }}>
          <SocialGlyph kind={l.key}/>
          <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{l.text}</span>
        </a>
      ))}
    </div>
  );
}

function SocialGlyph({ kind }) {
  const common = { width: 13, height: 13, viewBox: '0 0 24 24', fill: 'none', stroke: '#1a1a18', strokeWidth: 1.7, strokeLinecap: 'round', strokeLinejoin: 'round' };
  if (kind === 'ig') {
    return (
      <svg {...common} aria-hidden="true">
        <rect x="3" y="3" width="18" height="18" rx="5"/>
        <circle cx="12" cy="12" r="4"/>
        <circle cx="17.5" cy="6.5" r="0.6" fill="#1a1a18"/>
      </svg>
    );
  }
  if (kind === 'tt') {
    return (
      <svg {...common} aria-hidden="true">
        <path d="M14 3v11.5a3.5 3.5 0 1 1-3-3.46"/>
        <path d="M14 5.5A5 5 0 0 0 19 9"/>
      </svg>
    );
  }
  return (
    <svg {...common} aria-hidden="true">
      <circle cx="12" cy="12" r="9"/>
      <path d="M3.5 9h17M3.5 15h17M12 3a15 15 0 0 1 0 18a15 15 0 0 1 0-18z"/>
    </svg>
  );
}

// One published outfit, linking to its own public page at /<username>/<slug>.
function PublishedOutfitCard({ outfit, onOpen }) {
  const items = outfit.items || [];
  const when = outfit.published_at
    ? new Date(outfit.published_at).toLocaleDateString(undefined, { month: 'short', year: 'numeric' })
    : '';
  return (
    <div onClick={onOpen} data-outfit-slug={outfit.slug} style={{
      cursor: 'pointer', borderRadius: 14, overflow: 'hidden',
      background: '#fff', border: '1px solid rgba(20,20,18,0.08)',
    }}>
      <div style={{ background: '#FAFAF7' }}>
        {items.length > 0
          ? <OutfitBoard outfit={{ items }}/>
          : <div style={{
              aspectRatio: '1 / 1', display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: '#a8a39d', fontSize: 12, letterSpacing: '0.1em', textTransform: 'uppercase',
            }}>Empty board</div>}
      </div>
      <div style={{ padding: '14px 16px 16px', borderTop: '1px solid rgba(20,20,18,0.06)' }}>
        <div style={{
          fontFamily: "'Instrument Serif',serif", fontStyle: 'italic', fontSize: 19,
          letterSpacing: '-0.01em', lineHeight: 1.2,
        }}>{outfit.title || 'Untitled outfit'}</div>
        <div style={{ marginTop: 6, fontSize: 11.5, color: '#8a8580', display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <span>{items.length} {items.length === 1 ? 'piece' : 'pieces'}</span>
          {outfit.mood && <><span>·</span><span>{outfit.mood}</span></>}
          {when && <><span>·</span><span>{when}</span></>}
        </div>
      </div>
    </div>
  );
}

// Avatar with no upload behind it: the initial of the creator's name. Thin
// wrapper over the shared Avatar so the nav, the Studio, the directory and the
// profile all render the same circle.
function InitialAvatar({ name, username, size = 44, src = null }) {
  const source = String(name || username || '?').replace(/^@/, '');
  return (
    <Avatar
      creator={{ handle: username || source, avatar: (source[0] || '?').toUpperCase(), avatarUrl: src }}
      size={size}
    />
  );
}

const profileBtnPrimary = {
  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',
};
const profileBtnGhost = {
  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',
};

Object.assign(window, { ProfileScreen, PublishedOutfitCard, InitialAvatar, SocialLinks });
