// screens-main.jsx — Home, Explore, Profile, Outfit Detail
const { useState: useStateM, useMemo: useMemoM, useEffect: useEffectM, useRef: useRefM } = React;

// ─── Home ──────────────────────────────────────────────────────────────────
function HomeScreen({ go, density }) {
  const { OUTFITS, MOODS, TRENDING_IDS } = window.DRIPCHECK_DATA;
  const trending = TRENDING_IDS.map(id => OUTFITS.find(o => o.id === id)).filter(Boolean);
  const [tab, setTab] = useStateM('trending');
  const visible = trending; // exactly 9, ordered as curated

  return (
    <div>
      {/* Hero */}
      <section style={{ padding: '64px 40px 24px', position: 'relative' }}>
        <div style={{ maxWidth: 1080, marginInline: 'auto' }}>
          <h1 style={{
            margin: 0, fontSize: 'clamp(48px, 7vw, 104px)', lineHeight: 0.96,
            letterSpacing: '-0.04em', fontWeight: 400,
            maxWidth: '14ch',
          }}>
            Create shoppable outfit checks from <em style={{ fontFamily: "'Instrument Serif',serif", fontStyle: 'italic', fontWeight: 400 }}>any</em> product URL.
          </h1>
          <p style={{
            marginTop: 28, fontSize: 18, lineHeight: 1.55, maxWidth: '52ch', color: '#3a3a36',
          }}>
            Build visual outfits, share your style, and let your audience shop every piece. Paste a link from any store, we pull the image, brand, name and price. You arrange the look.
          </p>
          <div style={{ marginTop: 36, display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            <button onClick={() => go({ name: 'dashboard' })} style={btnPrimary}>Create your first outfit</button>
            <button onClick={() => go({ name: 'explore' })} style={btnGhost}>Explore outfits</button>
          </div>
          {/* The avatar strip and its "2,400+ creators publishing weekly" used
              to be five demo profiles and a made-up number. The real creator
              count lives on the Creators page, counted from published work. */}
        </div>
      </section>

      {/* Filter chips + tabs */}
      <section style={{ padding: '40px 40px 16px' }}>
        <div style={{ maxWidth: 1280, marginInline: 'auto', display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16 }}>
          <div>
            <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#8a8580', marginBottom: 10 }}>This week</div>
            <h2 style={{ margin: 0, fontSize: 36, letterSpacing: '-0.02em', fontWeight: 400 }}>Trending outfit checks</h2>
          </div>
          <div style={{ display: 'flex', gap: 22, fontSize: 12, letterSpacing: '0.14em', textTransform: 'uppercase' }}>
            {['trending','newest','most-saved'].map(t => (
              <button key={t} onClick={() => setTab(t)} style={{
                appearance: 'none', border: 'none', background: 'transparent', cursor: 'pointer', padding: '4px 0',
                color: tab === t ? '#1a1a18' : '#8a8580', fontWeight: 500,
                borderBottom: tab === t ? '1px solid #1a1a18' : '1px solid transparent',
                fontFamily: 'inherit',
              }}>{t.replace('-', ' ')}</button>
            ))}
          </div>
        </div>
      </section>

      {/* Outfit grid — exactly 9 in a 3×3 */}
      <section style={{ padding: '24px 40px 40px' }}>
        <div style={{
          maxWidth: 1280, marginInline: 'auto',
          display: 'grid',
          gridTemplateColumns: 'repeat(3, 1fr)',
          gap: 24,
        }}>
          {visible.map(o => <OutfitCard key={o.id} outfit={o} onClick={() => go({ name: 'outfit', id: o.id })} density="regular"/>)}
        </div>
        <div style={{ maxWidth: 1280, marginInline: 'auto', marginTop: 28, display: 'flex', justifyContent: 'center' }}>
          <button onClick={() => go({ name: 'explore' })} style={btnGhost}>See all outfits →</button>
        </div>
      </section>

      {/* Editorial pull-quote */}
      <section style={{ padding: '80px 40px', borderTop: '1px solid rgba(20,20,18,0.06)', marginTop: 40 }}>
        <div style={{ maxWidth: 980, marginInline: 'auto', textAlign: 'center' }}>
          <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#8a8580', marginBottom: 22 }}>How it works</div>
          <p style={{
            fontFamily: "'Instrument Serif',serif", fontStyle: 'italic',
            fontSize: 'clamp(28px, 4vw, 52px)', lineHeight: 1.15, letterSpacing: '-0.01em',
            margin: 0, color: '#1a1a18',
          }}>
            Paste a link. We pull the photo, brand and price.<br/>You arrange it like a magazine. Your audience shops it like a closet.
          </p>
        </div>
        <div style={{ maxWidth: 1080, marginInline: 'auto', marginTop: 64, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 32 }}>
          {[
            ['01', 'Paste any product link', 'A link from almost any online store — anything with an image. We parse the page so you don’t have to download anything.'],
            ['02', 'Arrange the look', 'Drag, resize, rotate. Mix in artwork, polaroids, mood images. Save drafts, version freely.'],
            ['03', 'Publish & share', 'Get a clean URL. Every item is clickable. Affiliate links and analytics included.'],
          ].map(([n, t, body]) => (
            <div key={n}>
              <div style={{ fontFamily: "'Instrument Serif',serif", fontSize: 28, fontStyle: 'italic', color: '#8a8580' }}>{n}</div>
              <div style={{ marginTop: 8, fontSize: 17, fontWeight: 500, letterSpacing: '-0.01em' }}>{t}</div>
              <div style={{ marginTop: 8, fontSize: 14, color: '#5a5a54', lineHeight: 1.55 }}>{body}</div>
            </div>
          ))}
        </div>
      </section>

      {/* Featured creators row */}
      <section style={{ padding: '40px 40px 0' }}>
        <div style={{ maxWidth: 1280, marginInline: 'auto' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 28 }}>
            <h2 style={{ margin: 0, fontSize: 36, letterSpacing: '-0.02em', fontWeight: 400 }}>Creators we’re watching</h2>
            <button onClick={() => go({ name: 'creators' })} style={linkBtn}>All creators →</button>
          </div>
          <FeaturedCreators go={go} limit={3}/>
        </div>
      </section>

      <Footer/>
    </div>
  );
}

// A real creator, as returned by mb_list_creators(): their own name, bio and
// location, with how many outfits they have actually published.
function CreatorCard({ creator, onClick }) {
  return (
    <div onClick={onClick} data-creator={creator.username} style={{
      cursor: 'pointer', padding: 22, borderRadius: 14,
      background: '#FAFAF7', border: '1px solid rgba(20,20,18,0.06)',
      display: 'flex', flexDirection: 'column', gap: 14,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <InitialAvatar name={creator.displayName} username={creator.username} size={44} src={creator.avatarUrl}/>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 16, letterSpacing: '-0.01em', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {creator.displayName || '@' + creator.username}
          </div>
          <div style={{ fontSize: 12, color: '#8a8580' }}>
            @{creator.username}{creator.location ? ' · ' + creator.location : ''}
          </div>
        </div>
      </div>

      {creator.bio && (
        <div style={{ fontSize: 13.5, color: '#3a3a36', lineHeight: 1.5 }}>{creator.bio}</div>
      )}

      {/* The board itself, composed the way the creator arranged it — the same
          preview My outfits shows — rather than one product photo lifted out
          of it. It's their most-viewed published board, or their most recent
          one if nothing has been viewed yet. */}
      {creator.topOutfit && creator.topOutfit.items.length > 0 && (
        <div title={creator.topOutfit.title} style={{
          borderRadius: 10, overflow: 'hidden',
          background: '#FAFAF7', border: '1px solid rgba(20,20,18,0.05)',
        }}>
          <OutfitBoard outfit={{ items: creator.topOutfit.items }}/>
        </div>
      )}

      <div style={{ marginTop: 'auto', fontSize: 11.5, color: '#8a8580', letterSpacing: '0.06em' }}>
        {creator.publishedCount} {creator.publishedCount === 1 ? 'OUTFIT' : 'OUTFITS'} PUBLISHED
      </div>
    </div>
  );
}

// Real creators for the home page. Renders nothing at all while there are
// none — an empty grid is better than three invented profiles.
function FeaturedCreators({ go, limit = 3 }) {
  const [creators, setCreators] = useStateM([]);
  const [loading, setLoading] = useStateM(true);

  useEffectM(() => {
    let cancelled = false;
    (async () => {
      const res = await window.MBProfile.listCreators(limit);
      if (cancelled) return;
      setCreators(res.creators || []);
      setLoading(false);
    })();
    return () => { cancelled = true; };
  }, [limit]);

  if (loading) {
    return <div style={{ fontSize: 13, color: '#8a8580' }}>Loading creators…</div>;
  }
  if (!creators.length) {
    return (
      <div style={{
        padding: '40px 28px', borderRadius: 14, textAlign: 'center',
        background: '#FAFAF7', border: '1px dashed rgba(20,20,18,0.14)',
      }}>
        <div style={{ fontSize: 15, color: '#3a3a36' }}>No published creators yet.</div>
        <p style={{ marginTop: 8, fontSize: 13, color: '#8a8580', lineHeight: 1.6 }}>
          Publish an outfit and your profile is the first one here.
        </p>
        <button onClick={() => go({ name: 'signup' })} style={{ ...btnPrimary, marginTop: 16 }}>
          Create an account
        </button>
      </div>
    );
  }
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 24 }}>
      {creators.map(c => (
        <CreatorCard key={c.username} creator={c} onClick={() => go({ name: 'profile', username: c.username })}/>
      ))}
    </div>
  );
}

// ─── Explore ────────────────────────────────────────────────────────────────
function ExploreScreen({ go, density, slug }) {
  const { OUTFITS, MOODS } = window.DRIPCHECK_DATA;
  const STYLE_PAGES = window.STYLE_PAGES;
  const stylePage = slug && STYLE_PAGES[slug];
  const titleCaseStyle = (s) => s.replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
  // For non-curated styles, synthesise a light page so the slug still has its own URL + heading.
  const effectivePage = stylePage || (slug ? {
    label: titleCaseStyle(slug),
    h1: titleCaseStyle(slug) + ' Outfit Ideas',
    filter: (o) => o.mood === slug || o.mood === slug.replace(/-/g, ' '),
    _synthetic: true,
  } : null);

  // Single-select navigation via slug. Multi-mood filter retained for non-slug page.
  const [activeMood, setActiveMood] = useStateM([]);
  const [season, setSeason] = useStateM('any');
  const [sort, setSort] = useStateM('trending');
  const [q, setQ] = useStateM('');
  const [moodQuery, setMoodQuery] = useStateM('');
  const MOOD_LIBRARY = window.DRIPCHECK_DATA.MOOD_LIBRARY || [];
  const moodMatches = moodQuery.trim()
    ? MOOD_LIBRARY.filter(m => m.replace(/[^a-z]/gi, '').includes(moodQuery.toLowerCase().replace(/[^a-z]/gi, ''))).slice(0, 14)
    : [];

  const toggleMood = (m) => setActiveMood(prev => prev.includes(m) ? prev.filter(x => x !== m) : [...prev, m]);

  // Apply per-page SEO meta tags when slug changes.
  useEffectM(() => {
    if (window.applyStyleMeta) window.applyStyleMeta(slug || null);
    return () => { if (window.applyStyleMeta) window.applyStyleMeta(null); };
  }, [slug]);

  const filtered = useMemoM(() => {
    let r = OUTFITS;
    if (effectivePage && effectivePage.filter) {
      r = r.filter(effectivePage.filter);
    } else if (activeMood.length) {
      r = r.filter(o => activeMood.includes(o.mood));
    }
    if (!effectivePage && season !== 'any') r = r.filter(o => o.season === season || o.season === 'all');
    if (q) {
      const qq = q.toLowerCase();
      r = r.filter(o => o.title.toLowerCase().includes(qq) || o.items.some(i => i.brand.toLowerCase().includes(qq) || i.name.toLowerCase().includes(qq)));
    }
    if (sort === 'most-saved') r = [...r].sort((a, b) => b.saves - a.saves);
    return r;
  }, [activeMood, season, sort, q, OUTFITS, effectivePage, slug]);

  const goToStyle = (s) => go({ name: 'explore', slug: s });
  const clearStyle = () => go({ name: 'explore' });

  return (
    <div>
      <section style={{ padding: '56px 40px 16px' }}>
        <div style={{ maxWidth: 1280, marginInline: 'auto' }}>
          {effectivePage ? (
            <>
              <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#8a8580' }}>
                <button onClick={clearStyle} style={{
                  appearance: 'none', border: 'none', background: 'transparent', cursor: 'pointer',
                  color: '#8a8580', letterSpacing: '0.22em', textTransform: 'uppercase', fontSize: 11,
                  fontFamily: 'inherit', padding: 0,
                }}>Explore</button>
                <span style={{ margin: '0 8px', color: '#c8c4be' }}>/</span>
                <span style={{ color: '#1a1a18' }}>{effectivePage.label}</span>
              </div>
              <h1 style={{ margin: '10px 0 0', fontSize: 56, fontWeight: 400, letterSpacing: '-0.03em' }}>{effectivePage.h1}</h1>
            </>
          ) : (
            <>
              <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#8a8580' }}>Explore</div>
              <h1 style={{ margin: '10px 0 0', fontSize: 56, fontWeight: 400, letterSpacing: '-0.03em' }}>Find your fit.</h1>
            </>
          )}
        </div>
      </section>

      <section style={{ padding: '24px 40px', position: 'sticky', top: 64, zIndex: 30, background: 'rgba(250,249,247,0.92)', backdropFilter: 'blur(12px)', borderBottom: '1px solid rgba(20,20,18,0.06)' }}>
        <div style={{ maxWidth: 1280, marginInline: 'auto', display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={{
            flex: '1 1 280px', maxWidth: 360,
            display: 'flex', alignItems: 'center', gap: 8,
            padding: '10px 14px', border: '1px solid rgba(20,20,18,0.14)', borderRadius: 999,
            background: '#fff',
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#8a8580" strokeWidth="1.8"><circle cx="11" cy="11" r="7"/><path d="M21 21l-5-5"/></svg>
            <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search brands, items, creators" style={{
              flex: 1, border: 'none', outline: 'none', background: 'transparent', fontSize: 13, fontFamily: 'inherit',
            }}/>
          </div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', flex: 1 }}>
            {/* "All" pill — clears slug to /explore/ */}
            <button onClick={clearStyle} style={{
              appearance: 'none', cursor: 'pointer', padding: '7px 12px', borderRadius: 999,
              fontSize: 11.5, letterSpacing: '0.04em', fontFamily: 'inherit',
              border: '1px solid',
              borderColor: !effectivePage && activeMood.length === 0 ? '#1a1a18' : 'rgba(20,20,18,0.14)',
              background: !effectivePage && activeMood.length === 0 ? '#1a1a18' : 'transparent',
              color: !effectivePage && activeMood.length === 0 ? '#FAFAF7' : '#1a1a18',
            }}>All</button>
            {/* Style chips — clicking navigates to /explore/[slug]/ */}
            {Object.entries(STYLE_PAGES).map(([s, page]) => {
              const isActive = slug === s;
              return (
                <button key={s} onClick={() => goToStyle(s)} style={{
                  appearance: 'none', cursor: 'pointer', padding: '7px 12px', borderRadius: 999,
                  fontSize: 11.5, letterSpacing: '0.04em', fontFamily: 'inherit',
                  border: '1px solid',
                  borderColor: isActive ? '#1a1a18' : 'rgba(20,20,18,0.14)',
                  background: isActive ? '#1a1a18' : 'transparent',
                  color: isActive ? '#FAFAF7' : '#1a1a18',
                }}>{page.label}</button>
              );
            })}
            {/* Extra moods the creator has already applied (beyond curated pages) */}
            {activeMood.map(m => (
              <button key={m} onClick={() => toggleMood(m)} style={{
                appearance: 'none', cursor: 'pointer', padding: '7px 12px', borderRadius: 999,
                fontSize: 11.5, letterSpacing: '0.04em', fontFamily: 'inherit',
                border: '1px solid #1a1a18', background: '#1a1a18', color: '#FAFAF7',
                display: 'inline-flex', alignItems: 'center', gap: 6, textTransform: 'capitalize',
              }}>{m}<span style={{ opacity: 0.6, fontSize: 13 }}>×</span></button>
            ))}
            {/* Mood finder — searchable access to the full style vocabulary */}
            <div style={{ position: 'relative' }}>
              <div style={{
                display: 'inline-flex', alignItems: 'center', gap: 6,
                padding: '7px 12px', borderRadius: 999, background: '#fff',
                border: '1px solid rgba(20,20,18,0.14)',
              }}>
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#8a8580" strokeWidth="1.8"><circle cx="11" cy="11" r="7"/><path d="M21 21l-5-5"/></svg>
                <input value={moodQuery} onChange={(e) => setMoodQuery(e.target.value)} placeholder="Find a style…" style={{
                  border: 'none', outline: 'none', background: 'transparent', fontSize: 11.5,
                  fontFamily: 'inherit', width: 96,
                }}/>
              </div>
              {moodMatches.length > 0 && (
                <div style={{
                  position: 'absolute', top: 'calc(100% + 6px)', left: 0, zIndex: 40,
                  width: 260, maxHeight: 240, overflowY: 'auto',
                  background: '#FAFAF7', border: '1px solid rgba(20,20,18,0.1)', borderRadius: 12,
                  boxShadow: '0 20px 50px -20px rgba(20,20,18,0.3)', padding: 6,
                  display: 'flex', flexWrap: 'wrap', gap: 6,
                }}>
                  {moodMatches.map(m => {
                    const token = m.replace(/[^a-z]/gi, '').toLowerCase();
                    const on = activeMood.includes(token);
                    return (
                      <button key={m} onClick={() => { goToStyle(token); setMoodQuery(''); }} style={{
                        appearance: 'none', cursor: 'pointer', padding: '6px 11px', borderRadius: 999,
                        fontSize: 11.5, fontFamily: 'inherit', textTransform: 'capitalize',
                        border: '1px solid', borderColor: on ? '#1a1a18' : 'rgba(20,20,18,0.14)',
                        background: on ? '#1a1a18' : 'transparent', color: on ? '#FAFAF7' : '#1a1a18',
                      }}>{m}</button>
                    );
                  })}
                </div>
              )}
            </div>
          </div>
          {!effectivePage && (
            <select value={season} onChange={(e) => setSeason(e.target.value)} style={selectStyle}>
              <option value="any">Any season</option>
              <option value="spring">Spring</option>
              <option value="summer">Summer</option>
              <option value="autumn">Autumn</option>
              <option value="winter">Winter</option>
            </select>
          )}
          <select value={sort} onChange={(e) => setSort(e.target.value)} style={selectStyle}>
            <option value="trending">Trending</option>
            <option value="most-saved">Most saved</option>
            <option value="newest">Newest</option>
          </select>
        </div>
      </section>

      <section style={{ padding: '32px 40px 40px' }}>
        <div style={{ maxWidth: 1280, marginInline: 'auto', marginBottom: 18, fontSize: 12, color: '#8a8580' }}>
          {filtered.length} {filtered.length === 1 ? 'outfit' : 'outfits'} {effectivePage ? `· ${effectivePage.label}` : (activeMood.length ? `· ${activeMood.join(', ')}` : '')}
        </div>
        <div style={{
          maxWidth: 1280, marginInline: 'auto',
          display: 'grid',
          gridTemplateColumns: `repeat(${density === 'compact' ? 4 : density === 'comfy' ? 2 : 3}, 1fr)`,
          gap: density === 'compact' ? 16 : density === 'comfy' ? 32 : 24,
        }}>
          {filtered.map(o => <OutfitCard key={o.id} outfit={o} onClick={() => go({ name: 'outfit', id: o.id })} density={density}/>)}
        </div>
        {filtered.length === 0 && (
          <div style={{ maxWidth: 600, marginInline: 'auto', textAlign: 'center', padding: '80px 0', color: '#8a8580', fontFamily: "'Instrument Serif',serif", fontStyle: 'italic', fontSize: 24 }}>
            Nothing here yet. Loosen the filters?
          </div>
        )}
      </section>

      {/* SEO copy — only on style pages, below the grid */}
      {stylePage && (
        <section style={{ padding: '40px 40px 80px', borderTop: '1px solid rgba(20,20,18,0.06)', marginTop: 24 }}>
          <div style={{ maxWidth: 720, marginInline: 'auto', textAlign: 'center' }}>
            <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#8a8580', marginBottom: 18 }}>About this style</div>
            <h2 style={{ margin: 0, fontSize: 32, fontWeight: 400, letterSpacing: '-0.02em', fontFamily: "'Instrument Serif',serif", fontStyle: 'italic' }}>{stylePage.h1}</h2>
            <p style={{ marginTop: 22, fontSize: 16, lineHeight: 1.7, color: '#3a3a36', textWrap: 'pretty' }}>{stylePage.seoText}</p>
            {/* Cross-link to a few other styles for SEO + UX */}
            <div style={{ marginTop: 36, fontSize: 11.5, letterSpacing: '0.04em', color: '#8a8580' }}>Related styles</div>
            <div style={{ marginTop: 12, display: 'flex', justifyContent: 'center', gap: 8, flexWrap: 'wrap' }}>
              {Object.entries(STYLE_PAGES)
                .filter(([s]) => s !== slug)
                .slice(0, 6)
                .map(([s, page]) => (
                  <button key={s} onClick={() => goToStyle(s)} style={{
                    appearance: 'none', cursor: 'pointer', padding: '7px 14px', borderRadius: 999,
                    fontSize: 11.5, letterSpacing: '0.04em', fontFamily: 'inherit',
                    border: '1px solid rgba(20,20,18,0.14)', background: 'transparent', color: '#1a1a18',
                  }}>{page.label}</button>
                ))}
            </div>
          </div>
        </section>
      )}

      <Footer/>
    </div>
  );
}

// ─── Outfit Detail ──────────────────────────────────────────────────────────
function OutfitDetailScreen({ outfitId, go }) {
  const { OUTFITS } = window.DRIPCHECK_DATA;
  const outfit = OUTFITS.find(o => o.id === outfitId) || OUTFITS[0];
  const [hoveredItem, setHoveredItem] = useStateM(null);
  const [saved, setSaved] = useStateM(false);
  const [format, setFormat] = useStateM('original');

  const FORMATS = {
    original: { label: 'Original',    ratio: '1 / 1',  maxW: '100%', badge: '1:1' },
    story:    { label: 'IG Story',    ratio: '9 / 16', maxW: 440,    badge: '9:16' },
    post:     { label: 'IG Post',     ratio: '4 / 5',  maxW: 560,    badge: '4:5' },
    tiktok:   { label: 'TikTok',      ratio: '9 / 16', maxW: 440,    badge: '9:16' },
  };
  const fmt = FORMATS[format];

  const totalPrice = outfit.items.reduce((sum, i) => sum + (i.price || 0), 0);
  const related = OUTFITS.filter(o => o.id !== outfit.id && o.mood === outfit.mood).slice(0, 4);

  return (
    <div>
      <section style={{ padding: '40px 40px 24px' }}>
        <div style={{ maxWidth: 1280, marginInline: 'auto' }}>
          <button onClick={() => go({ name: 'home' })} style={linkBtn}>← Back</button>
        </div>
      </section>

      <section style={{ padding: '0 40px 64px' }}>
        <div style={{ maxWidth: 1280, marginInline: 'auto', display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 48 }}>
          {/* Board */}
          <div>
            {/* Format selector */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
              <span style={{ fontSize: 10.5, letterSpacing: '0.16em', textTransform: 'uppercase', color: '#8a8580', marginRight: 4 }}>Format</span>
              {Object.entries(FORMATS).map(([key, f]) => (
                <button key={key} onClick={() => setFormat(key)} style={{
                  appearance: 'none', cursor: 'pointer', fontFamily: 'inherit',
                  padding: '7px 12px', borderRadius: 999, fontSize: 11.5,
                  border: '1px solid',
                  borderColor: format === key ? '#1a1a18' : 'rgba(20,20,18,0.14)',
                  background: format === key ? '#1a1a18' : 'transparent',
                  color: format === key ? '#FAFAF7' : '#1a1a18',
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                }}>
                  {f.label}
                  <span style={{ fontSize: 9.5, opacity: 0.6, fontVariantNumeric: 'tabular-nums' }}>{f.badge}</span>
                </button>
              ))}
            </div>
            <div style={{ position: 'relative', borderRadius: 18, overflow: 'hidden', background: '#FAFAF7', boxShadow: '0 30px 80px -30px rgba(20,20,18,0.18)', maxWidth: fmt.maxW, marginInline: format === 'original' ? 0 : 'auto', transition: 'max-width .3s ease' }}>
              <div style={{ position: 'relative', width: '100%', aspectRatio: fmt.ratio, background: '#FAFAF7', transition: 'aspect-ratio .3s ease' }}>
                {outfit.items.map(it => (
                  <div key={it.id}
                       onMouseEnter={() => setHoveredItem(it.id)}
                       onMouseLeave={() => setHoveredItem(null)}
                       style={{
                         position: 'absolute',
                         left: `${it.x}%`, top: `${it.y}%`,
                         width: `${it.w}%`, height: `${it.h}%`,
                         transform: `rotate(${it.rot}deg) ${hoveredItem === it.id ? 'scale(1.05)' : 'scale(1)'}`,
                         transformOrigin: 'center',
                         transition: 'transform .3s ease, filter .3s ease',
                         filter: hoveredItem && hoveredItem !== it.id ? 'opacity(.35)' : 'none',
                         cursor: 'pointer',
                       }}>
                    <ProductImage item={it}/>
                    {/* dot pin */}
                    <div style={{
                      position: 'absolute', top: '50%', left: '50%',
                      width: 10, height: 10, marginLeft: -5, marginTop: -5, borderRadius: '50%',
                      background: '#1a1a18',
                      boxShadow: '0 0 0 4px rgba(250,249,247,0.9), 0 0 0 5px rgba(20,20,18,0.2)',
                      opacity: hoveredItem === it.id ? 1 : 0,
                      transform: `rotate(${-it.rot}deg)`,
                      transition: 'opacity .2s',
                    }}/>
                  </div>
                ))}
              </div>
              <div style={{
                position: 'absolute', top: 18, left: 18,
                fontSize: 10.5, letterSpacing: '0.18em', textTransform: 'uppercase',
                padding: '5px 10px', borderRadius: 999,
                background: 'rgba(250,249,247,0.86)', backdropFilter: 'blur(6px)',
              }}>{outfit.mood} · {outfit.season}</div>
            </div>

            <div style={{ marginTop: 24, display: 'flex', gap: 12, flexWrap: 'wrap' }}>
              <button onClick={() => setSaved(!saved)} style={{ ...btnGhost, padding: '12px 18px', display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill={saved ? '#1a1a18' : 'none'} stroke="#1a1a18" strokeWidth="1.6"><path d="M6 4h12v17l-6-4-6 4z"/></svg>
                {saved ? 'Saved' : 'Save'} · {outfit.saves.toLocaleString()}
              </button>
              <button style={{ ...btnGhost, padding: '12px 18px', display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#1a1a18" strokeWidth="1.6"><path d="M4 12v7h16v-7M16 6l-4-4-4 4M12 2v14"/></svg>
                Share
              </button>
              <button style={{ ...btnGhost, padding: '12px 18px' }}>Copy link</button>
              <button style={{ ...btnGhost, padding: '12px 18px' }}>Remix</button>
            </div>
          </div>

          {/* Product list */}
          <div>
            <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#8a8580' }}>Sample board</div>
            <h1 style={{ margin: '10px 0 0', fontSize: 44, lineHeight: 1.05, letterSpacing: '-0.02em', fontWeight: 400, fontFamily: "'Instrument Serif',serif" }}><em>{outfit.title}</em></h1>
            {/* These example boards aren't anyone's work, so there is no
                creator to credit and nobody to follow. Real boards live on
                their creator's profile at /<username>. */}
            <div style={{ marginTop: 14, fontSize: 13, color: '#5a5a54', lineHeight: 1.55 }}>
              An example of what an outfit board looks like.{' '}
              <button onClick={() => go({ name: 'creators' })} style={{
                appearance: 'none', border: 'none', background: 'transparent', padding: 0,
                cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, color: '#1a1a18',
                textDecoration: 'underline', textUnderlineOffset: 3,
              }}>See boards from real creators →</button>
            </div>

            <div style={{ marginTop: 32, paddingBottom: 16, borderBottom: '1px solid rgba(20,20,18,0.06)', display: 'flex', justifyContent: 'space-between' }}>
              <div style={{ fontSize: 12, letterSpacing: '0.16em', textTransform: 'uppercase', color: '#8a8580' }}>The look · {outfit.items.length} pieces</div>
              <div style={{ fontSize: 12, color: '#8a8580' }}>Total <span style={{ color: '#1a1a18', fontWeight: 500 }}>{MBMoney.format(totalPrice, 'USD')}</span></div>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column' }}>
              {outfit.items.map(it => (
                <div key={it.id}
                     onMouseEnter={() => setHoveredItem(it.id)}
                     onMouseLeave={() => setHoveredItem(null)}
                     style={{
                       display: 'flex', gap: 14, alignItems: 'center',
                       padding: '18px 0', borderBottom: '1px solid rgba(20,20,18,0.06)',
                       background: hoveredItem === it.id ? 'rgba(20,20,18,0.02)' : 'transparent',
                       transition: 'background .15s',
                       marginInline: hoveredItem === it.id ? -10 : 0,
                       paddingInline: hoveredItem === it.id ? 10 : 0,
                       borderRadius: hoveredItem === it.id ? 10 : 0,
                     }}>
                  <div style={{ width: 64, height: 64, flexShrink: 0, borderRadius: 8, background: '#fff', border: '1px solid rgba(20,20,18,0.06)' }}>
                    <ProductImage item={it}/>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: '#8a8580' }}>{it.brand}</div>
                    <div style={{ fontSize: 14, marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.name}</div>
                    {/* Editorial demo boards; their fixtures in data.js are USD. */}
                    <div style={{ fontSize: 12, color: '#8a8580', marginTop: 2 }}>{MBMoney.format(it.price, it.currency || 'USD')} · {it.store}</div>
                  </div>
                  <button style={{
                    appearance: 'none', border: '1px solid #1a1a18', background: '#1a1a18',
                    color: '#FAFAF7', padding: '9px 14px', borderRadius: 999, fontSize: 10.5,
                    letterSpacing: '0.16em', textTransform: 'uppercase', cursor: 'pointer', fontFamily: 'inherit',
                  }}>Shop</button>
                </div>
              ))}
            </div>

            <div style={{ marginTop: 32, padding: 20, background: '#F2EFE7', borderRadius: 14 }}>
              <div style={{ fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: '#5a5550', marginBottom: 8 }}>Notes from the creator</div>
              <div style={{ fontFamily: "'Instrument Serif',serif", fontStyle: 'italic', fontSize: 18, lineHeight: 1.4, color: '#1a1a18' }}>
                “Built around the indigo. Everything else stays quiet — the print earns its place because the rest of the fit doesn’t argue with it.”
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Related */}
      <section style={{ padding: '40px 40px 0', borderTop: '1px solid rgba(20,20,18,0.06)' }}>
        <div style={{ maxWidth: 1280, marginInline: 'auto' }}>
          <h2 style={{ margin: 0, fontSize: 28, fontWeight: 400, letterSpacing: '-0.02em' }}>More like this</h2>
          <div style={{ marginTop: 24, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 18 }}>
            {related.map(o => (
              <OutfitCard key={o.id} outfit={o} onClick={() => go({ name: 'outfit', id: o.id })}/>
            ))}
          </div>
        </div>
      </section>
      <Footer/>
    </div>
  );
}

// ─── Creator Profile ───────────────────────────────────────────────────────
// ─── shared styles ──────────────────────────────────────────────────────────
const btnPrimary = {
  appearance: 'none', border: '1px solid #1a1a18', background: '#1a1a18',
  color: '#FAFAF7', padding: '14px 22px', borderRadius: 999,
  fontSize: 12, letterSpacing: '0.16em', textTransform: 'uppercase',
  fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
};
const btnGhost = {
  appearance: 'none', border: '1px solid rgba(20,20,18,0.18)', background: 'transparent',
  color: '#1a1a18', padding: '14px 22px', borderRadius: 999,
  fontSize: 12, letterSpacing: '0.16em', textTransform: 'uppercase',
  fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
};
const linkBtn = {
  appearance: 'none', border: 'none', background: 'transparent', cursor: 'pointer',
  padding: 0, fontSize: 12, letterSpacing: '0.14em', textTransform: 'uppercase',
  fontWeight: 500, color: '#1a1a18', fontFamily: 'inherit',
};
const selectStyle = {
  padding: '10px 14px', borderRadius: 999, border: '1px solid rgba(20,20,18,0.14)',
  background: '#fff', fontSize: 12, letterSpacing: '0.04em', fontFamily: 'inherit',
  cursor: 'pointer', appearance: 'none',
};

Object.assign(window, {
  HomeScreen, ExploreScreen, OutfitDetailScreen, CreatorCard, FeaturedCreators,
  btnPrimary, btnGhost, linkBtn, selectStyle,
});
