// ========== SAVED / WISHLIST + JOURNAL ==========

const SavedPage = ({ nav, saved, toggleSave, openProvider, openProduct, addToCart }) => {
  const [tab, setTab] = React.useState('all');
  const savedProviders = PROVIDERS.filter(p => saved.providers.includes(p.id));
  const savedProducts = PRODUCTS.filter(p => saved.products.includes(p.id));
  const total = savedProviders.length + savedProducts.length;

  return (
    <div className="fade-in">
      <div className="container">
        <div className="page-head" style={{paddingTop: 40}}>
          <div>
            <div className="eyebrow">Your mood board</div>
            <h1>Saved <span className="i">for later.</span></h1>
          </div>
          <div style={{display:'flex', gap: 8}}>
            <button className="btn btn-outline" onClick={() => nav('explore')}>Find more</button>
            <button className="btn btn-brand" onClick={() => nav('marketplace')}>Shop goods</button>
          </div>
        </div>

        <div className="saved-tabs">
          <button className={tab==='all'?'active':''} onClick={()=>setTab('all')}>All <span>{total}</span></button>
          <button className={tab==='providers'?'active':''} onClick={()=>setTab('providers')}>Providers <span>{savedProviders.length}</span></button>
          <button className={tab==='products'?'active':''} onClick={()=>setTab('products')}>Products <span>{savedProducts.length}</span></button>
        </div>

        {total === 0 && (
          <div className="saved-empty">
            <div className="empty-art">✦</div>
            <h3>Nothing saved yet</h3>
            <p>Tap the heart on any provider or product to start your mood board.</p>
            <div style={{display:'flex', gap: 8, justifyContent:'center', marginTop: 18}}>
              <button className="btn btn-brand" onClick={() => nav('explore')}>Browse providers</button>
              <button className="btn btn-outline" onClick={() => nav('marketplace')}>Browse shop</button>
            </div>
          </div>
        )}

        {total > 0 && (
          <div className="moodboard">
            {(tab === 'all' || tab === 'providers') && savedProviders.map(p => (
              <div key={'p-'+p.id} className="mood-tile mood-provider" onClick={() => openProvider(p.id)}>
                <div className="mood-cover">
                  <PremPortrait seed={p.username} name={p.name} size="100%" radius="0"/>
                  <button className="mood-heart active" onClick={(e) => { e.stopPropagation(); toggleSave('providers', p.id); }}>
                    <Icon name="heart" size={14}/>
                  </button>
                </div>
                <div className="mood-body">
                  <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap: 8}}>
                    <div>
                      <div style={{fontWeight: 600, fontSize: 14}}>{p.name}</div>
                      <div style={{fontSize: 11.5, color:'var(--muted)'}}>{p.tagline}</div>
                    </div>
                    <Stars n={Math.round(p.rating)} size={10}/>
                  </div>
                  <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginTop: 10, fontSize: 12}}>
                    <span style={{color:'var(--muted)'}}>{p.area}</span>
                    <span style={{fontFamily:'Fraunces, serif', fontSize: 16, fontWeight: 500}}>from ${p.priceMin}</span>
                  </div>
                </div>
              </div>
            ))}
            {(tab === 'all' || tab === 'products') && savedProducts.map(p => (
              <div key={'pr-'+p.id} className="mood-tile mood-product" onClick={() => openProduct(p.id)}>
                <div className="mood-cover">
                  <Ph tone={p.tone} style={{width:'100%', height:'100%', fontSize: 11}}>{p.name.split(' ').slice(0,2).join(' ')}</Ph>
                  <button className="mood-heart active" onClick={(e) => { e.stopPropagation(); toggleSave('products', p.id); }}>
                    <Icon name="heart" size={14}/>
                  </button>
                </div>
                <div className="mood-body">
                  <div style={{fontSize: 11, color:'var(--muted)'}}>{p.seller}</div>
                  <div style={{fontWeight: 600, fontSize: 13.5, marginTop: 2, lineHeight: 1.25}}>{p.name}</div>
                  <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginTop: 10}}>
                    <span style={{fontFamily:'Fraunces, serif', fontSize: 20, fontWeight: 500}}>${p.price}</span>
                    <button className="btn btn-brand btn-sm" onClick={(e)=>{e.stopPropagation(); addToCart(p);}}>Add</button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

// ========== JOURNAL / EDITORIAL ==========
const JOURNAL = [
  {
    id: 'j1', kind: 'feature',
    cat: 'Heritage', title: 'How Barbadian hair oil traditions made it to Brooklyn',
    dek: 'Three generations of women. One bottle. A diaspora story.',
    readTime: '8 min read', date: 'April 18, 2026',
    author: 'Aiyana Phillips', tone: 'coral',
  },
  {
    id: 'j2', kind: 'interview',
    cat: 'The Interview', title: 'Jasmine Morgan on why she almost quit, and what brought her back',
    dek: 'The Kingston silk-press specialist opens her studio, and her book.',
    readTime: '12 min read', date: 'April 14, 2026',
    author: 'Keisha Alleyne', tone: 'lav',
  },
  {
    id: 'j3', kind: 'guide',
    cat: 'The Glossary', title: 'Every knot, twist and cornrow: a field guide',
    dek: 'From Fulani braids to goddess locs, named and explained.',
    readTime: '6 min read', date: 'April 10, 2026',
    author: 'Rena Williams', tone: 'peach',
  },
  {
    id: 'j4', kind: 'essay',
    cat: 'Essay', title: 'What "Caribbean beauty" actually means in 2026',
    dek: 'Past tourism brochures. Toward something that belongs to us.',
    readTime: '5 min read', date: 'April 6, 2026',
    author: 'Safiya Marsden', tone: 'mint',
  },
];

const JournalPage = ({ nav, toast }) => {
  return (
    <div className="fade-in journal-page">
      <section className="journal-hero">
        <div className="container">
          <div className="eyebrow">The Journal · Issue 04</div>
          <h1>Stories from the <em>studios</em>,<br/>the shops, and the streets.</h1>
          <p>A dispatch from the people shaping Caribbean beauty, from Kingston to Bridgetown to Brooklyn.</p>
        </div>
      </section>

      <section className="section">
        <div className="container">
          <div className="journal-grid">
            {JOURNAL.map((a, i) => {
              // Use real provider portfolio photos as journal covers — same
              // strategy as the landing's journal preview. Different photo
              // per card so the page doesn't look repetitive.
              const provs = (typeof window !== 'undefined' && Array.isArray(window.PROVIDERS)) ? window.PROVIDERS : [];
              const photos = provs
                .filter(p => (p.portfolio && p.portfolio[0]) || p.photo)
                .map(p => (p.portfolio && p.portfolio[0]) || p.photo);
              const cover = photos[i % Math.max(1, photos.length)] || null;
              return (
                <article key={a.id} className={`journal-card ${i===0 ? 'big':''}`}
                  onClick={() => toast(`Opening "${a.title.slice(0, 40)}…"`)}>
                  <div className="journal-cover" style={{position:'relative', overflow:'hidden'}}>
                    {cover ? (
                      <>
                        <img src={cover} alt={a.cat} style={{position:'absolute', inset: 0, width:'100%', height:'100%', objectFit:'cover'}}/>
                        <div className="journal-overlay"/>
                        <div className="journal-cat">{a.cat}</div>
                      </>
                    ) : (
                      <PremPortrait seed={a.id} name={a.cat} size="100%" radius="0">
                        <div className="journal-overlay"/>
                        <div className="journal-cat">{a.cat}</div>
                      </PremPortrait>
                    )}
                  </div>
                  <div className="journal-body">
                    <h3>{a.title}</h3>
                    <p className="dek">{a.dek}</p>
                    <div className="journal-meta">
                      <span>{a.author}</span>
                      <span>·</span>
                      <span>{a.readTime}</span>
                      <span>·</span>
                      <span>{a.date}</span>
                    </div>
                  </div>
                </article>
              );
            })}
          </div>

          <div className="journal-subscribe">
            <div>
              <div className="eyebrow">The Weekly</div>
              <h2>One dispatch. <em>Every Sunday.</em></h2>
              <p>The week in Caribbean beauty. New studios, new products, new voices. No spam, ever.</p>
            </div>
            <form className="subscribe-form" onSubmit={(e)=>{e.preventDefault(); toast('Subscribed. Welcome to The Weekly ✦');}}>
              <input placeholder="you@domain.com" type="email" defaultValue="chloe@gmail.com"/>
              <button className="btn btn-brand" type="submit">Subscribe</button>
            </form>
          </div>
        </div>
      </section>
    </div>
  );
};

Object.assign(window, { SavedPage, JournalPage, JOURNAL });
