// ========== BOOKING MODAL ==========
const BookingModal = ({ open, provider, service, onClose, onConfirm }) => {
  const [step, setStep] = React.useState(0);
  const [selDate, setSelDate] = React.useState(22);
  const [selTime, setSelTime] = React.useState('2:30');

  React.useEffect(() => { if (open) setStep(0); }, [open]);

  if (!provider) return null;
  const svc = service || { name: 'Silk Press + Trim', d: '2h 45m', price: 210 };
  const deposit = Math.round(svc.price * 0.2);

  const days = [];
  for (let i = 0; i < 3; i++) days.push({ dow: '', dim: true });
  for (let d = 22; d <= 30; d++) days.push({ d, dow: 'T' });

  return (
    <div className={`modal-overlay ${open ? 'open' : ''}`} onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="step-dots">
          {[0,1,2].map(i => <div key={i} className={`d ${i < step ? 'done' : i === step ? 'active' : ''}`}/>)}
        </div>
        <div className="modal-head">
          <div>
            <div className="eyebrow" style={{marginBottom: 6}}>
              {step === 0 ? 'Pick a time' : step === 1 ? 'Your details' : 'Pay deposit'}
            </div>
            <h2>
              {step === 0 ? 'When works best?' : step === 1 ? 'A few details' : 'Confirm & pay'}
            </h2>
          </div>
          <button className="close" onClick={onClose}><Icon name="x" size={14}/></button>
        </div>

        <div className="modal-body">
          {step === 0 && <>
            <div className="eyebrow" style={{marginBottom: 10}}>April 2026</div>
            <div className="date-picker">
              {['S','M','T','W','T','F','S'].map((d, i) => <div key={i} className="dp dow">{d}</div>)}
              {[...Array(3)].map((_, i) => <div key={`p${i}`} className="dp disabled"/>)}
              {[22,23,24,25,26,27,28,29,30].map(d => (
                <div key={d} className={`dp ${selDate === d ? 'selected' : ''} ${d === 27 ? 'disabled' : ''}`} onClick={() => d !== 27 && setSelDate(d)}>
                  {d}
                </div>
              ))}
            </div>

            <div className="eyebrow" style={{margin: '20px 0 10px'}}>Available times · Wed, Apr {selDate}</div>
            <div className="time-grid">
              {['9:00','10:30','11:30','1:00','2:30','4:00','5:30','6:30'].map((t, i) => (
                <button key={t} className={`time-slot ${selTime === t ? 'selected' : ''}`} disabled={i === 2} onClick={() => setSelTime(t)}>
                  {t}
                </button>
              ))}
            </div>

            <div className="book-summary">
              <div className="r"><span style={{color:'var(--muted)'}}>Service</span><span style={{fontWeight: 600}}>{svc.name}</span></div>
              <div className="r"><span style={{color:'var(--muted)'}}>With</span><span>{provider.name}</span></div>
              <div className="r"><span style={{color:'var(--muted)'}}>Duration</span><span>{svc.d || '2h 45m'}</span></div>
              <div className="r tot"><span>Total</span><span>${svc.price}</span></div>
            </div>

            <button className="btn btn-brand" style={{width:'100%', marginTop: 16}} onClick={() => setStep(1)}>
              Continue <Icon name="arrowRight" size={14}/>
            </button>
          </>}

          {step === 1 && <>
            <div className="field"><label>Full name</label><input defaultValue="Chloé Alexander"/></div>
            <div className="field"><label>Phone</label><input defaultValue="+1 (876) 555-0142"/></div>
            <div className="field"><label>Notes for your stylist (optional)</label>
              <textarea rows="3" placeholder="Anything they should know: length, preferences, sensitivities..."/></div>
            <div style={{background:'var(--sand)', borderRadius: 12, padding: 14, fontSize: 12.5, color:'var(--ink-2)'}}>
              <strong>Free cancellation</strong> up to 24 hours before your appointment. Your deposit is refundable.
            </div>
            <div style={{display:'flex', gap: 8, marginTop: 20}}>
              <button className="btn btn-outline" onClick={() => setStep(0)}>Back</button>
              <button className="btn btn-brand" style={{flex: 1}} onClick={() => setStep(2)}>Continue to payment</button>
            </div>
          </>}

          {step === 2 && <>
            <div style={{display:'flex', gap: 10, marginBottom: 16}}>
              {['Card','Apple Pay','Google Pay'].map((m, i) => (
                <button key={m} className={i === 0 ? 'btn btn-primary' : 'btn btn-outline'} style={{flex: 1}}>{m}</button>
              ))}
            </div>
            <div className="field"><label>Card number</label><input defaultValue="4242 4242 4242 4242"/></div>
            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap: 12}}>
              <div className="field"><label>Expiry</label><input defaultValue="04/29"/></div>
              <div className="field"><label>CVC</label><input defaultValue="123"/></div>
            </div>

            <div className="book-summary">
              <div className="r"><span style={{color:'var(--muted)'}}>{svc.name}</span><span>${svc.price}</span></div>
              <div className="r"><span style={{color:'var(--muted)'}}>Due today (20% deposit)</span><span style={{fontWeight: 600}}>${deposit}</span></div>
              <div className="r"><span style={{color:'var(--muted)'}}>Balance at appointment</span><span>${svc.price - deposit}</span></div>
              <div className="r tot"><span>Total</span><span>${svc.price}</span></div>
            </div>

            <div style={{display:'flex', gap: 8, marginTop: 20}}>
              <button className="btn btn-outline" onClick={() => setStep(1)}>Back</button>
              <button className="btn btn-brand" style={{flex: 1}} onClick={() => onConfirm({ provider, service: svc, date: selDate, time: selTime })}>
                Pay ${deposit} & confirm
              </button>
            </div>
            <div style={{textAlign:'center', fontSize: 11, color:'var(--muted)', marginTop: 12}}>Secured by Stripe · PCI compliant</div>
          </>}
        </div>
      </div>
    </div>
  );
};

// ========== TOPBAR ==========
const TopBar = ({ view, nav, cartCount, openCart, openNotif, savedCount = 0, auth, signOut }) => {
  const [menuOpen, setMenuOpen] = React.useState(false);
  const links = [
    { k: 'explore', l: 'Explore', i: 'map' },
    { k: 'bookings', l: 'Bookings', i: 'calendar' },
    { k: 'messages', l: 'Messages', i: 'msg' },
    { k: 'marketplace', l: 'Shop', i: 'shop' },
    { k: 'journal', l: 'Journal', i: 'sparkles' },
    { k: 'seller-dashboard', l: 'Seller', i: 'chart' },
  ];
  const openLogin = () => { if (typeof window !== 'undefined') window.__loginMode = 'login'; nav('login'); };
  const openRegister = () => { if (typeof window !== 'undefined') window.__loginMode = 'signup'; nav('login'); };
  return (
    <div className="topbar">
      <div className="topbar-inner">
        <div className="brand" onClick={() => nav('landing')} style={{cursor:'pointer'}}>
          <img src={(window.__resources && window.__resources.logo) || "assets/caribglow-logo.png"} alt=""/>
          <span><span className="b1">Carib</span><span className="b2">Glow</span></span>
        </div>
        <div className="navlinks">
          {links.map(l => (
            <div key={l.k} className={`navlink ${view === l.k ? 'active' : ''}`} onClick={() => nav(l.k)}>
              <Icon name={l.i} size={14} className="ico"/> {l.l}
            </div>
          ))}
        </div>
        <div className="topbar-right">
          {!auth ? (
            <>
              <button className="btn btn-ghost btn-sm" onClick={openLogin} style={{marginRight: 4}}>Log in</button>
              <button className="btn btn-brand btn-sm" onClick={openRegister} style={{marginRight: 8}}>Register</button>
            </>
          ) : null}
          <button className="icon-btn" onClick={() => nav('saved')} title="Saved" style={{position:'relative'}}>
            <Icon name="heart" size={16}/>
            {savedCount > 0 && <div className="dot" style={{top: 5, right: 5, background: 'var(--coral)', fontSize: 9, width: 14, height: 14, color:'#fff', display:'grid', placeItems:'center', borderRadius:'50%'}}>{savedCount}</div>}
          </button>
          <button className="icon-btn" onClick={openCart}>
            <Icon name="cart" size={16}/>
            {cartCount > 0 && <div className="dot" style={{top: 5, right: 5, background: 'var(--coral)', fontSize: 9, width: 14, height: 14, color:'#fff', display:'grid', placeItems:'center', borderRadius:'50%'}}>{cartCount}</div>}
          </button>
          <button className="icon-btn notif-btn" onClick={openNotif} title="Notifications">
            <Icon name="bell" size={16}/>
            <div className="dot" style={{background:'var(--coral)'}}/>
          </button>
          {auth ? (
            <div style={{position:'relative'}}>
              <div className="avatar-btn" onClick={() => setMenuOpen(m => !m)} style={{cursor:'pointer', padding: 2, background:'linear-gradient(135deg,#f5b800,#ff9a6b)', borderRadius:'50%'}} title={`${auth.name} · ${auth.role}`}>
                <div style={{width:'100%', height:'100%', borderRadius:'50%', background:'#fff', padding: 2}}>
                  <PremPortrait seed={auth.email || auth.name} name={auth.name} size={24}/>
                </div>
              </div>
              {menuOpen && (
                <>
                  <div onClick={() => setMenuOpen(false)} style={{position:'fixed', inset: 0, zIndex: 998}}/>
                  <div style={{position:'absolute', top:'calc(100% + 8px)', right: 0, width: 220, background:'#fff', border:'1px solid var(--line)', borderRadius: 12, boxShadow:'0 12px 36px rgba(0,0,0,0.12)', zIndex: 999, overflow:'hidden'}}>
                    <div style={{padding:'12px 14px', borderBottom:'1px solid var(--line)'}}>
                      <div style={{fontSize: 13, fontWeight: 600}}>{auth.name}</div>
                      <div style={{fontSize: 11, color:'var(--muted)', marginTop: 2}}>
                        {auth.email} · <span style={{textTransform:'capitalize'}}>{auth.role}</span>
                      </div>
                    </div>
                    {[
                      { k: auth.role === 'provider' ? 'seller-dashboard' : 'bookings', l: auth.role === 'provider' ? 'Dashboard' : 'My bookings' },
                      { k: 'saved', l: 'Saved' },
                      { k: 'glow-circle', l: 'Glow Circle' },
                      { k: 'referral', l: 'Refer & earn' },
                    ].map(m => (
                      <div key={m.k} onClick={() => { setMenuOpen(false); nav(m.k); }}
                        style={{padding:'10px 14px', fontSize: 13, cursor:'pointer', borderBottom:'1px solid var(--line)'}}
                        onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-soft)'}
                        onMouseLeave={e => e.currentTarget.style.background = '#fff'}>
                        {m.l}
                      </div>
                    ))}
                    <div onClick={() => { setMenuOpen(false); signOut && signOut(); }}
                      style={{padding:'10px 14px', fontSize: 13, cursor:'pointer', color:'var(--coral)', fontWeight: 500}}
                      onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-soft)'}
                      onMouseLeave={e => e.currentTarget.style.background = '#fff'}>
                      Sign out
                    </div>
                  </div>
                </>
              )}
            </div>
          ) : (
            <div className="avatar-btn" onClick={openLogin} style={{cursor:'pointer', background:'var(--bg-soft)', border:'1px solid var(--line)', display:'grid', placeItems:'center'}} title="Log in">
              <Icon name="user" size={14}/>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

// ========== AUTH WALL ==========
const AuthWall = ({ requiredRole, view, nav }) => {
  const viewLabels = {
    'explore': { title: 'Discover Caribbean beauty pros', body: 'Create a free account to browse verified providers, see real reviews, and book in seconds.' },
    'provider-profile': { title: 'See full provider details', body: 'Sign in to view portfolios, availability, and book this provider.' },
    'bookings': { title: 'Your bookings live here', body: 'Sign in to view, reschedule, and manage your appointments.' },
    'messages': { title: 'Messages are private', body: 'Sign in to chat with your providers and keep your conversations secure.' },
    'marketplace': { title: 'Shop the CaribGlow marketplace', body: 'Create an account to browse products, save favorites, and check out in seconds.' },
    'product-detail': { title: 'Sign in to shop', body: 'Create a free account to add items to your cart and check out.' },
    'journal': { title: 'The Journal is for members', body: 'Join CaribGlow to read stories, tutorials, and inspiration from top Caribbean pros.' },
    'saved': { title: 'Your saves live here', body: 'Sign in to see the providers and products you\'ve favorited.' },
    'glow-circle': { title: 'Glow Circle is for members', body: 'Sign in to view your tier, points, and perks.' },
    'checkout': { title: 'Sign in to check out', body: 'Create an account to complete your order and track shipping.' },
    'order-tracking': { title: 'Sign in to track orders', body: 'Your orders are tied to your account.' },
    'seller-dashboard': { title: 'For providers only', body: 'Register as a provider to manage bookings, listings, and payouts.' },
    'provider-setup': { title: 'For providers only', body: 'Create a provider account to set up your profile.' },
    'product-editor': { title: 'For providers only', body: 'Sign in as a provider to edit your listings.' },
    'analytics': { title: 'For providers only', body: 'Track your performance from your provider dashboard.' },
    'embed': { title: 'For providers only', body: 'Grab your embed widget after signing in as a provider.' },
    'qr': { title: 'For providers only', body: 'Generate your booking QR after signing in as a provider.' },
  };
  const v = viewLabels[view] || { title: 'Sign in required', body: 'Create a free account or log in to continue.' };
  const isProvider = requiredRole === 'provider';
  const toLogin = () => { if (typeof window !== 'undefined') window.__loginMode = 'login'; nav('login'); };
  const toRegister = () => { if (typeof window !== 'undefined') window.__loginMode = 'signup'; nav('login'); };
  return (
    <div className="fade-in" style={{minHeight:'calc(100vh - 64px)', display:'grid', placeItems:'center', padding:'60px 20px', background:'linear-gradient(180deg,#FFF9F4 0%, #FFFFFF 100%)'}}>
      <div style={{maxWidth: 520, width:'100%', textAlign:'center', padding:'48px 40px', background:'#fff', border:'1px solid var(--line)', borderRadius: 20, boxShadow:'0 24px 60px rgba(30,22,15,0.08)'}}>
        <div style={{width: 72, height: 72, borderRadius: '50%', background: isProvider ? 'linear-gradient(135deg,#F5B800,#FF9A6B)' : 'linear-gradient(135deg,var(--primary),var(--primary-deep))', display:'grid', placeItems:'center', margin:'0 auto 22px', color:'#fff'}}>
          <Icon name={isProvider ? 'chart' : 'user'} size={30}/>
        </div>
        <div className="eyebrow" style={{color:'var(--primary-deep)', marginBottom: 8}}>
          {isProvider ? 'Provider access' : 'Members only'}
        </div>
        <h2 style={{fontFamily:'Fraunces, serif', fontSize: 30, fontWeight: 500, letterSpacing:'-0.02em', marginBottom: 12, lineHeight: 1.15}}>
          {v.title}
        </h2>
        <p style={{color:'var(--ink-2)', fontSize: 15, lineHeight: 1.55, marginBottom: 28, maxWidth: 400, margin:'0 auto 28px'}}>
          {v.body}
        </p>
        <div style={{display:'flex', gap: 10, justifyContent:'center', flexWrap:'wrap'}}>
          <button className="btn btn-brand btn-lg" onClick={toRegister}>
            {isProvider ? 'Register as provider' : 'Create free account'}
          </button>
          <button className="btn btn-outline btn-lg" onClick={toLogin}>
            Log in
          </button>
        </div>
        <div style={{marginTop: 24, paddingTop: 20, borderTop:'1px solid var(--line)', fontSize: 13, color:'var(--muted)'}}>
          Not sure yet? <span onClick={() => nav('landing')} style={{color:'var(--primary-deep)', fontWeight: 600, cursor:'pointer', textDecoration:'underline'}}>Back to home</span> to learn more.
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { BookingModal, TopBar, AuthWall });
