// ========== EXPLORE PAGE ==========
const ExplorePage = ({ nav, openProvider, saved = {providers:[],products:[]}, toggleSave = () => {} }) => {
  const [cat, setCat] = React.useState('all');
  const [view, setView] = React.useState('split');
  const [hoveredId, setHoveredId] = React.useState(null);
  const filtered = PROVIDERS.filter(p => cat === 'all' || p.category === cat);

  return (
    <div className="fade-in">
      <section className="explore-head">
        <div className="container">
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom: 20, gap: 24}}>
            <div>
              <div className="eyebrow">Discover</div>
              <h1 style={{fontFamily:'Fraunces, serif', fontSize: 44, margin: '6px 0 0', fontWeight: 500, letterSpacing:'-0.025em', lineHeight: 1}}>
                Beauty artists <span style={{fontStyle:'italic', color:'var(--primary-deep)'}}>near you</span>
              </h1>
            </div>
            <div style={{color:'var(--muted)', fontSize: 13.5}}>
              <span style={{fontWeight: 600, color:'var(--ink)'}}>{filtered.length}</span> providers · Kingston & nearby
            </div>
          </div>

          <div className="search-bar">
            <div className="search-cell">
              <label>Service</label>
              <input defaultValue="Hair"/>
            </div>
            <div className="search-cell">
              <label>Location</label>
              <input defaultValue="New Kingston"/>
            </div>
            <div className="search-cell">
              <label>When</label>
              <input defaultValue="This week"/>
            </div>
            <button className="search-submit"><Icon name="search" size={18}/></button>
          </div>

          <div className="filters-row">
            {CATEGORIES.map(c => (
              <button key={c.id} className={`chip ${cat === c.id ? 'active' : ''}`} onClick={() => setCat(c.id)}>
                {c.label}
              </button>
            ))}
            <button className="chip"><Icon name="filter" size={13}/> More filters</button>
            <div className="view-toggle">
              <button className={view === 'split' ? 'active' : ''} onClick={() => setView('split')}>
                <Icon name="map" size={12}/> Split
              </button>
              <button className={view === 'list' ? 'active' : ''} onClick={() => setView('list')}>
                List
              </button>
            </div>
          </div>
        </div>
      </section>

      <div className="container">
        <div className="explore-layout" style={view === 'list' ? {gridTemplateColumns: '1fr'} : {}}>
          <div className="provider-list" style={view === 'list' ? {gridTemplateColumns: 'repeat(4, 1fr)'} : {}}>
            {filtered.map(p => (
              <div key={p.id} className="provider-card"
                onMouseEnter={() => setHoveredId(p.id)}
                onMouseLeave={() => setHoveredId(null)}
                onClick={() => openProvider(p.id)}>
                <div className="provider-cover" style={{position:'relative', overflow:'hidden'}}>
                  <PremPortrait seed={p.username} name={p.name} size="100%" radius="0" photoUrl={(p.portfolio && p.portfolio[0]) || p.photo}/>
                  <button className={`fav ${saved.providers.includes(p.id) ? 'active' : ''}`} onClick={e => { e.stopPropagation(); toggleSave('providers', p.id); }}
                    style={saved.providers.includes(p.id) ? {color:'var(--coral)', background:'#fff'} : {}}>
                    <Icon name="heart" size={14} stroke={1.6}/>
                  </button>
                  {p.priceMin > 0 && <div className="price-pill">from ${p.priceMin}</div>}
                </div>
                <div className="provider-body">
                  <div className="provider-name">
                    <div className="n">
                      {p.name}
                      {p.verified && <svg width="14" height="14" viewBox="0 0 24 24" fill="var(--teal)"><path d="M12 2 9 6H4v5L2 14l2 3v5h5l3 4 3-4h5v-5l2-3-2-3V6h-5zm-1 10 2 2 4-4 1.5 1.5L13 17l-3.5-3.5z"/></svg>}
                    </div>
                    <div className="provider-rating">
                      <Icon name="star" size={12}/> {p.rating}
                      <span style={{color:'var(--muted)', fontWeight: 400}}>({p.reviews})</span>
                    </div>
                  </div>
                  <div className="provider-meta">
                    {p.tagline} · {p.area}
                  </div>
                  <div className="provider-services">
                    {p.services.slice(0, 2).map(s => <span key={s} className="badge">{s}</span>)}
                    <span className="badge badge-indigo">{p.distance}</span>
                  </div>
                </div>
              </div>
            ))}
          </div>

          {view === 'split' && (
            <div className="map-wrap">
              <div className="map-canvas">
                <svg viewBox="0 0 100 100" preserveAspectRatio="none">
                  <path d="M 5,30 Q 25,25 35,35 T 65,40 Q 80,45 95,35" fill="none" stroke="#b4cde5" strokeWidth="0.4"/>
                  <path d="M 10,60 Q 35,55 50,62 T 85,70" fill="none" stroke="#b4cde5" strokeWidth="0.3"/>
                  <path d="M 30,10 L 35,90" fill="none" stroke="rgba(0,0,0,0.04)" strokeWidth="0.2"/>
                  <path d="M 70,5 L 65,95" fill="none" stroke="rgba(0,0,0,0.04)" strokeWidth="0.2"/>
                  <path d="M 5,45 L 95,55" fill="none" stroke="rgba(0,0,0,0.04)" strokeWidth="0.2"/>
                  <circle cx="45" cy="50" r="2" fill="#b4cde5"/>
                  <text x="47" y="52" fontSize="2" fill="#6b6584" fontFamily="Inter, sans-serif">New Kingston</text>
                </svg>
                {filtered.map(p => (
                  <div key={p.id} className={`map-pin ${hoveredId === p.id ? 'active' : ''}`}
                    style={{left: `${p.pos.x}%`, top: `${p.pos.y}%`}}
                    onMouseEnter={() => setHoveredId(p.id)}
                    onClick={() => openProvider(p.id)}>
                    <div className="p">${p.priceMin}+</div>
                  </div>
                ))}
                <div style={{position:'absolute', bottom: 16, right: 16, display:'flex', flexDirection:'column', gap: 6}}>
                  <button style={{width: 36, height: 36, borderRadius: 10, background:'#fff', boxShadow:'var(--shadow-md)', display:'grid', placeItems:'center'}}>
                    <Icon name="plus" size={16}/>
                  </button>
                  <button style={{width: 36, height: 36, borderRadius: 10, background:'#fff', boxShadow:'var(--shadow-md)', display:'grid', placeItems:'center'}}>
                    <Icon name="minus" size={16}/>
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

// ========== PROVIDER PROFILE ==========
const ProviderProfilePage = ({ providerId, nav, openBooking, saved = {providers:[],products:[]}, toggleSave = () => {} }) => {
  const p = PROVIDERS.find(x => x.id === providerId) || PROVIDERS[0] || { name: 'Provider', area: '', rating: 0, reviews: 0, services: [], servicesFull: [], portfolio: [], joinedYear: 2024, tone: 'indigo' };
  const [tab, setTab] = React.useState('services');
  const [reviews, setReviews] = React.useState([]);

  const services = (p.servicesFull && p.servicesFull.length)
    ? p.servicesFull.map(s => ({ name: s.name, d: ((s.description || '') + (s.d ? ' · ' + s.d : ' · ' + (s.d || '60 min'))).trim().replace(/^· /, ''), price: s.price }))
    : (p.services || []).map(s => ({ name: s, d: 'Custom service', price: p.priceMin || 0 }));

  React.useEffect(() => {
    let alive = true;
    if (window.cgApi && p.id) {
      cgApi.providerReviews(p.id).then(rs => { if (alive) setReviews(rs || []); }).catch(() => {});
    }
    return () => { alive = false; };
  }, [p.id]);

  const coverPhoto = (p.portfolio && p.portfolio[0]) || p.photo || null;

  return (
    <div className="fade-in">
      <div className="container">
        <div className="profile-cover" style={coverPhoto ? {backgroundImage:`url(${coverPhoto})`, backgroundSize:'cover', backgroundPosition:'center'} : {}}>
          {!coverPhoto && <Ph tone={p.tone} style={{fontSize: 12}}>{p.name}</Ph>}
        </div>
        <div className="profile-head">
          <div className="profile-avatar" style={{overflow:'hidden'}}>
            <PremPortrait seed={p.username} name={p.name} size="100%" radius="0" photoUrl={p.photo}/>
          </div>
          <div className="profile-info">
            <div style={{display:'flex', gap: 10, alignItems:'center', marginBottom: 4}}>
              <span className="badge badge-verified">
                <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2 9 6H4v5L2 14l2 3v5h5l3 4 3-4h5v-5l2-3-2-3V6h-5z"/></svg>
                Verified
              </span>
              <span className="badge badge-indigo">Member since {p.joinedYear}</span>
            </div>
            <h1>{p.name}</h1>
            <div className="meta">
              <span><Icon name="star" size={13}/> <strong>{p.rating}</strong> ({p.reviews} reviews)</span>
              <span><Icon name="pin" size={13}/> {p.area}</span>
              <span><Icon name="tag" size={13}/> {p.tagline}</span>
              <span><Icon name="clock" size={13}/> Usually responds in under 1h</span>
            </div>
          </div>
          <div className="profile-cta">
            <button className="btn btn-ghost btn-sm" onClick={() => toggleSave('providers', p.id)} title="Save"
              style={{padding:'8px', width: 36, height: 36}}>
              <Icon name="heart" size={16}/>
            </button>
            <button className="btn btn-outline" onClick={() => nav('messages')}>
              <Icon name="msg" size={14}/> Message
            </button>
            <button className="btn btn-brand" onClick={() => openBooking(p)}>
              <Icon name="calendar" size={14}/> Book now
            </button>
          </div>
        </div>

        <div className="profile-tabs">
          {['services','portfolio','reviews','about'].map(t => (
            <button key={t} className={tab === t ? 'active' : ''} onClick={() => setTab(t)}>
              {t[0].toUpperCase() + t.slice(1)}
            </button>
          ))}
        </div>

        <div className="profile-grid">
          <div>
            {tab === 'services' && (
              <div className="card-soft" style={{padding: '8px 24px'}}>
                {services.map((s, i) => (
                  <div key={i} className="service-row">
                    <div>
                      <h4>{s.name}</h4>
                      <div className="d">{s.d}</div>
                    </div>
                    <div style={{display:'flex', alignItems:'center', gap: 20}}>
                      <div className="p">${s.price}</div>
                      <button className="btn btn-outline btn-sm" onClick={() => openBooking(p, s)}>Book</button>
                    </div>
                  </div>
                ))}
              </div>
            )}

            {tab === 'portfolio' && (
              <div className="portfolio-grid">
                {(p.portfolio && p.portfolio.length > 0) ? (
                  p.portfolio.map((url, i) => (
                    <div key={i} className="portfolio-tile" style={{overflow:'hidden'}}>
                      <img src={url} alt={`${p.name} portfolio ${i+1}`} style={{width:'100%', height:'100%', objectFit:'cover', display:'block'}}/>
                    </div>
                  ))
                ) : (
                  <div style={{gridColumn:'1 / -1', padding:'40px 24px', textAlign:'center', color:'var(--muted)', fontSize: 13}}>
                    {p.name} hasn't uploaded portfolio photos yet.
                  </div>
                )}
              </div>
            )}

            {tab === 'reviews' && (
              <div className="card-soft" style={{padding: '8px 24px'}}>
                <div style={{display:'flex', gap: 32, padding: '20px 0', borderBottom:'1px solid var(--line)'}}>
                  <div>
                    <div style={{fontFamily:'Fraunces, serif', fontSize: 56, fontWeight: 500, lineHeight: 1, letterSpacing:'-0.02em'}}>{p.rating}</div>
                    <Stars n={5} size={14}/>
                    <div style={{color:'var(--muted)', fontSize: 12, marginTop: 4}}>{p.reviews} reviews</div>
                  </div>
                  <div style={{flex: 1, display:'flex', flexDirection:'column', gap: 6, justifyContent:'center'}}>
                    {[5,4,3,2,1].map(n => (
                      <div key={n} style={{display:'flex', alignItems:'center', gap: 10, fontSize: 12}}>
                        <span style={{width: 10}}>{n}</span>
                        <div style={{flex: 1, height: 6, background:'var(--sand-2)', borderRadius: 999, overflow:'hidden'}}>
                          <div style={{width: `${[92,6,1,0.5,0.5][5-n]}%`, height:'100%', background:'var(--yellow)'}}/>
                        </div>
                        <span style={{width: 30, color:'var(--muted)'}}>{[92,6,1,0,0][5-n]}%</span>
                      </div>
                    ))}
                  </div>
                </div>
                {reviews.length === 0 ? (
                  <div style={{padding:'24px 0', color:'var(--muted)', fontSize: 13, textAlign:'center'}}>
                    No reviews yet for {p.name}.
                  </div>
                ) : reviews.map((r, i) => {
                  const cl = r.client || {};
                  const reviewerName = ((cl.firstName || '') + ' ' + (cl.lastName || '')).trim() || 'Client';
                  const dt = r.createdAt ? new Date(r.createdAt) : null;
                  const dateStr = dt ? dt.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : '';
                  return (
                    <div key={r.id || i} className="review-card">
                      <div className="review-head">
                        <PremPortrait seed={reviewerName} name={reviewerName} size={36} photoUrl={cl.profilePhotoUrl}/>
                        <div>
                          <div className="n">{reviewerName}</div>
                          <div className="d">{dateStr}</div>
                        </div>
                        <div style={{marginLeft: 'auto'}}><Stars n={Number(r.rating || 5)} size={12}/></div>
                      </div>
                      <div className="review-body">{r.comment || ''}</div>
                    </div>
                  );
                })}
              </div>
            )}

            {tab === 'about' && (
              <div className="card-soft" style={{padding: 28}}>
                <p style={{fontFamily:'Fraunces, serif', fontSize: 22, lineHeight: 1.45, margin: 0}}>
                  {(p._raw && p._raw.bio) || p.tagline || `${p.name} is a verified provider on CaribGlow${p.area ? ` based in ${p.area}` : ''}.`}
                </p>
                <div style={{marginTop: 20, display:'grid', gridTemplateColumns:'1fr 1fr', gap: 16}}>
                  <div>
                    <div className="eyebrow">Services</div>
                    <div style={{marginTop: 8, display:'flex', flexWrap:'wrap', gap: 6}}>
                      {(p.services || []).slice(0, 6).map(s =>
                        <span key={s} className="badge">{s}</span>
                      )}
                    </div>
                  </div>
                  <div>
                    <div className="eyebrow">Location</div>
                    <div style={{marginTop: 8}}>{p.area || 'Caribbean'}</div>
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* Booking rail */}
          <div className="booking-rail">
            <h3>Book with {p.name.split(' ')[0]}</h3>
            <div className="sub">Next available: Tomorrow at 11:30 AM</div>

            <div style={{display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap: 6, marginBottom: 14}}>
              {['Tue 22','Wed 23','Thu 24','Fri 25'].map((d, i) => (
                <button key={d} className={`time-slot ${i === 0 ? 'selected' : ''}`}>
                  <div style={{fontSize: 10, opacity: 0.7}}>{d.split(' ')[0]}</div>
                  <div style={{fontSize: 15, fontWeight: 600, marginTop: 2}}>{d.split(' ')[1]}</div>
                </button>
              ))}
            </div>

            <div className="eyebrow" style={{marginBottom: 8}}>Available times</div>
            <div className="time-grid">
              {['9:00', '11:30', '1:00', '2:30', '4:00', '5:30'].map((t, i) =>
                <button key={t} className={`time-slot ${i === 3 ? 'selected' : ''}`}>{t}</button>
              )}
            </div>

            <div style={{marginTop: 18, padding: 14, background: 'var(--sand)', borderRadius: 12}}>
              <div style={{display:'flex', justifyContent:'space-between', fontSize: 13}}>
                <span style={{color:'var(--muted)'}}>{(services[0] && services[0].name) || (p.services && p.services[0]) || 'Service'}</span>
                <span style={{fontWeight: 600}}>${(services[0] && services[0].price) || p.priceMin || 0}</span>
              </div>
              <div style={{display:'flex', justifyContent:'space-between', fontSize: 13, marginTop: 4}}>
                <span style={{color:'var(--muted)'}}>Deposit (20%)</span>
                <span>${Math.round(((services[0] && services[0].price) || p.priceMin || 0) * 0.2)}</span>
              </div>
            </div>

            <button className="btn btn-brand" style={{width:'100%', marginTop: 14}} onClick={() => openBooking(p, services[0])}>
              Continue to checkout <Icon name="arrowRight" size={14}/>
            </button>
            <div style={{textAlign:'center', fontSize: 11.5, color:'var(--muted)', marginTop: 10}}>
              Free cancellation up to 24h before
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { ExplorePage, ProviderProfilePage });
