// ========== PROVIDER ANALYTICS ==========
const AnalyticsPage = ({ nav }) => {
  const [range, setRange] = React.useState('30d');
  const viewsData = [45, 52, 48, 61, 55, 72, 68, 80, 75, 92, 85, 102, 118, 110, 124, 140, 132, 148, 162, 155, 178, 170, 190, 205, 198, 220, 212, 238, 245, 262];
  const maxViews = Math.max(...viewsData);

  const kpis = [
    { l: 'Profile views', v: '12,482', d: '+18%', up: true, spark:[4,5,5,6,6,7,8,9,9,10] },
    { l: 'Booking conversion', v: '8.4%', d: '+2.1pp', up: true, spark:[6,7,6,8,8,7,9,9,10,10] },
    { l: 'Avg booking value', v: '$142', d: '+$12', up: true, spark:[5,5,6,6,7,7,8,8,9,10] },
    { l: 'Repeat rate', v: '61%', d: '-3pp', up: false, spark:[8,8,7,7,7,6,6,6,5,6] },
  ];

  return (
    <div className="fade-in">
      <div className="container">
        <div className="page-head">
          <div>
            <div className="eyebrow">Provider</div>
            <h1><span className="i">Analytics</span></h1>
          </div>
          <div style={{display:'flex', gap: 4, background:'#fff', border:'1px solid var(--line)', borderRadius: 999, padding: 4}}>
            {[['7d','7 days'],['30d','30 days'],['90d','90 days'],['all','All time']].map(([k,l]) => (
              <button key={k} onClick={() => setRange(k)}
                className={range === k ? 'btn btn-ink btn-sm' : 'btn btn-ghost btn-sm'}
                style={{borderRadius: 999}}>{l}</button>
            ))}
          </div>
        </div>

        <div style={{display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap: 14, paddingBottom: 20}}>
          {kpis.map(k => (
            <div key={k.l} style={{background:'#fff', borderRadius: 18, padding: 20, border:'1px solid var(--line)'}}>
              <div style={{fontSize: 12, color:'var(--muted)', fontWeight: 500}}>{k.l}</div>
              <div style={{display:'flex', alignItems:'flex-end', justifyContent:'space-between', marginTop: 8}}>
                <div style={{fontFamily:'Fraunces, serif', fontSize: 36, fontWeight: 500, letterSpacing:'-0.02em', lineHeight: 1}}>{k.v}</div>
                <svg width="60" height="28" style={{overflow:'visible'}}>
                  <polyline points={k.spark.map((v, i) => `${i * 6},${28 - v * 2}`).join(' ')}
                    fill="none" stroke={k.up ? 'var(--ok)' : 'var(--err)'} strokeWidth="1.8"/>
                </svg>
              </div>
              <div style={{fontSize: 12, color: k.up ? 'var(--ok)' : 'var(--err)', fontWeight: 600, marginTop: 6}}>
                {k.up ? '↑' : '↓'} {k.d} vs last period
              </div>
            </div>
          ))}
        </div>

        <div style={{display:'grid', gridTemplateColumns:'2fr 1fr', gap: 14, paddingBottom: 20}}>
          <div style={{background:'#fff', borderRadius: 18, padding: 24, border:'1px solid var(--line)'}}>
            <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 16}}>
              <div>
                <div className="eyebrow">Profile views</div>
                <div style={{fontFamily:'Fraunces, serif', fontSize: 26, fontWeight: 500, marginTop: 4}}>Last 30 days</div>
              </div>
              <div style={{display:'flex', gap: 14, fontSize: 12}}>
                <div style={{display:'flex', alignItems:'center', gap: 6}}><div style={{width: 10, height: 10, borderRadius: 3, background:'var(--primary)'}}/> Views</div>
                <div style={{display:'flex', alignItems:'center', gap: 6}}><div style={{width: 10, height: 10, borderRadius: 3, background:'var(--coral)'}}/> Bookings</div>
              </div>
            </div>
            <svg viewBox="0 0 600 200" style={{width:'100%', height: 200}}>
              <defs>
                <linearGradient id="g1" x1="0" x2="0" y1="0" y2="1">
                  <stop offset="0" stopColor="#6366F1" stopOpacity="0.25"/>
                  <stop offset="1" stopColor="#6366F1" stopOpacity="0"/>
                </linearGradient>
              </defs>
              {[0,0.25,0.5,0.75,1].map(p => (
                <line key={p} x1="0" x2="600" y1={200 * p} y2={200 * p} stroke="var(--line)" strokeWidth="1"/>
              ))}
              <polygon fill="url(#g1)" points={`0,200 ${viewsData.map((v, i) => `${(i/29) * 600},${200 - (v/maxViews) * 180}`).join(' ')} 600,200`}/>
              <polyline fill="none" stroke="var(--primary)" strokeWidth="2.5"
                points={viewsData.map((v, i) => `${(i/29) * 600},${200 - (v/maxViews) * 180}`).join(' ')}/>
              <polyline fill="none" stroke="var(--coral)" strokeWidth="2.5" strokeDasharray="4 4"
                points={viewsData.map((v, i) => `${(i/29) * 600},${200 - ((v*0.08)/maxViews * 10) * 180}`).join(' ')}/>
            </svg>
            <div style={{display:'flex', justifyContent:'space-between', fontSize: 11, color:'var(--muted)', marginTop: 8}}>
              <span>Mar 23</span><span>Apr 1</span><span>Apr 8</span><span>Apr 15</span><span>Apr 22</span>
            </div>
          </div>

          <div style={{background:'#fff', borderRadius: 18, padding: 24, border:'1px solid var(--line)'}}>
            <div className="eyebrow">Top sources</div>
            <div style={{fontFamily:'Fraunces, serif', fontSize: 22, fontWeight: 500, margin:'4px 0 20px'}}>Where viewers come from</div>
            {[
              {n:'Direct / QR code', v: 42, c:'var(--primary)'},
              {n:'CaribGlow Search', v: 28, c:'var(--coral)'},
              {n:'Instagram bio link', v: 18, c:'var(--teal)'},
              {n:'Google search', v: 8, c:'var(--violet)'},
              {n:'Referrals', v: 4, c:'var(--yellow)'},
            ].map(s => (
              <div key={s.n} style={{marginBottom: 12}}>
                <div style={{display:'flex', justifyContent:'space-between', fontSize: 12.5, marginBottom: 4}}>
                  <span>{s.n}</span><strong>{s.v}%</strong>
                </div>
                <div style={{height: 6, background:'var(--sand)', borderRadius: 999, overflow:'hidden'}}>
                  <div style={{width: `${s.v}%`, height:'100%', background: s.c}}/>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap: 14, paddingBottom: 60}}>
          <div style={{background:'#fff', borderRadius: 18, padding: 24, border:'1px solid var(--line)'}}>
            <div className="eyebrow">Top services</div>
            <div style={{fontFamily:'Fraunces, serif', fontSize: 22, fontWeight: 500, margin:'4px 0 16px'}}>Revenue by service</div>
            {[
              {n:'Silk Press + Trim', v: 4840, b: 27},
              {n:'Deep Conditioning', v: 1620, b: 54},
              {n:'Blowout', v: 2280, b: 24},
              {n:'Bridal consult', v: 960, b: 4},
            ].map(s => (
              <div key={s.n} style={{display:'flex', justifyContent:'space-between', padding:'12px 0', borderBottom:'1px solid var(--line)'}}>
                <div>
                  <div style={{fontWeight: 500, fontSize: 14}}>{s.n}</div>
                  <div style={{fontSize: 12, color:'var(--muted)', marginTop: 2}}>{s.b} bookings</div>
                </div>
                <div style={{fontFamily:'Fraunces, serif', fontSize: 20, fontWeight: 500}}>${s.v}</div>
              </div>
            ))}
          </div>
          <div style={{background:'#fff', borderRadius: 18, padding: 24, border:'1px solid var(--line)'}}>
            <div className="eyebrow">Peak times</div>
            <div style={{fontFamily:'Fraunces, serif', fontSize: 22, fontWeight: 500, margin:'4px 0 16px'}}>When clients book</div>
            <div style={{display:'grid', gridTemplateColumns:'auto repeat(7, 1fr)', gap: 3, fontSize: 10.5}}>
              <div/>
              {['M','T','W','T','F','S','S'].map((d, i) => <div key={i} style={{textAlign:'center', color:'var(--muted)', fontWeight: 600}}>{d}</div>)}
              {['9a','12p','3p','6p','9p'].map((t, ti) => (
                <React.Fragment key={t}>
                  <div style={{color:'var(--muted)', paddingRight: 6, textAlign:'right'}}>{t}</div>
                  {[0,1,2,3,4,5,6].map(di => {
                    const h = ((ti * 7 + di * 3) * 37) % 100;
                    const heat = h > 70 ? 1 : h > 45 ? 0.6 : h > 20 ? 0.3 : 0.1;
                    return <div key={di} style={{aspectRatio: 1, borderRadius: 4, background: `rgba(99, 102, 241, ${heat})`}}/>;
                  })}
                </React.Fragment>
              ))}
            </div>
            <div style={{fontSize: 12.5, color:'var(--ink-2)', marginTop: 14, padding: 12, background:'var(--sand)', borderRadius: 10}}>
              💡 Your peak is <strong>Saturday 12p–6p</strong>. Add 2 slots to capture more demand.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ========== PRICING TIERS ==========
const PricingPage = ({ nav, toast }) => {
  const [annual, setAnnual] = React.useState(true);
  const tiers = [
    { k:'free', n:'Free', tag: 'Start here', p: 0, desc:'Everything to test the waters.', cta:'Current plan', disabled: true,
      features: ['Up to 3 services', 'Basic profile page', 'In-app messaging', 'Standard search placement', '5% booking fee'] },
    { k:'pro', n:'Pro', tag: 'Most popular', p: annual ? 19 : 24, desc:'For pros serious about growing.', cta:'Upgrade to Pro', highlight: true,
      features: ['Unlimited services', 'Analytics dashboard', 'QR code + embed widget', 'Custom URL glowcarib.com/you', 'Priority support', '3% booking fee'] },
    { k:'premium', n:'Premium', tag: 'Scale up', p: annual ? 49 : 59, desc:'Featured placement + team seats.', cta:'Upgrade to Premium',
      features: ['Everything in Pro, plus:', 'Featured in Explore (top row)', 'Custom branded booking page', '3 team seats', 'Instagram auto-sync', '2% booking fee'] },
  ];

  return (
    <div className="fade-in">
      <div className="container-narrow">
        <div style={{textAlign:'center', padding:'40px 0 20px'}}>
          <div className="eyebrow">Provider tiers</div>
          <h1 style={{fontFamily:'Fraunces, serif', fontSize: 60, fontWeight: 500, letterSpacing:'-0.03em', lineHeight: 1, margin:'10px 0 16px'}}>
            Your glow, <em style={{fontStyle:'italic', color:'var(--primary-deep)'}}>your pace</em>.
          </h1>
          <p style={{fontSize: 17, color:'var(--ink-2)', maxWidth: 560, margin:'0 auto', lineHeight: 1.5}}>
            Start free forever. Upgrade when your calendar fills up.
          </p>

          <div style={{display:'inline-flex', background:'#fff', border:'1px solid var(--line)', borderRadius: 999, padding: 4, marginTop: 24, gap: 4}}>
            {[['monthly','Monthly', false],['annual','Annual', true]].map(([k,l,a]) => (
              <button key={k} onClick={() => setAnnual(a)}
                className={annual === a ? 'btn btn-ink btn-sm' : 'btn btn-ghost btn-sm'}
                style={{borderRadius: 999, padding:'8px 16px'}}>
                {l} {a && <span style={{fontSize: 10, marginLeft: 6, color: annual === a ? '#fff' : 'var(--ok)', fontWeight: 700}}>SAVE 20%</span>}
              </button>
            ))}
          </div>
        </div>

        <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap: 16, padding:'40px 0 60px'}}>
          {tiers.map(t => (
            <div key={t.k} style={{
              background: t.highlight ? 'var(--ink)' : '#fff',
              color: t.highlight ? '#fff' : 'var(--ink)',
              borderRadius: 24,
              padding: 32,
              border: t.highlight ? 'none' : '1px solid var(--line)',
              position:'relative',
              boxShadow: t.highlight ? 'var(--shadow-xl)' : 'var(--shadow-sm)',
              transform: t.highlight ? 'scale(1.03)' : 'none',
            }}>
              {t.highlight && <div style={{position:'absolute', top: -12, left: 24, background:'var(--coral)', color:'#fff', fontSize: 10.5, fontWeight: 700, letterSpacing:'0.08em', padding:'5px 12px', borderRadius: 999}}>{t.tag.toUpperCase()}</div>}
              <div style={{fontSize: 11, fontWeight: 700, letterSpacing:'0.12em', textTransform:'uppercase', opacity: t.highlight ? 0.7 : 1, color: t.highlight ? '#fff' : 'var(--muted)'}}>{t.n}</div>
              <div style={{marginTop: 10, display:'flex', alignItems:'baseline', gap: 6}}>
                <span style={{fontFamily:'Fraunces, serif', fontSize: 56, fontWeight: 500, letterSpacing:'-0.03em', lineHeight: 1}}>${t.p}</span>
                <span style={{fontSize: 13, opacity: 0.7}}>/mo{annual ? ', billed yearly' : ''}</span>
              </div>
              <div style={{fontSize: 14, opacity: 0.8, marginTop: 10, marginBottom: 22, minHeight: 40}}>{t.desc}</div>

              <button className={t.highlight ? 'btn' : 'btn btn-outline'}
                style={{width:'100%', marginBottom: 22,
                  background: t.highlight ? '#fff' : '', color: t.highlight ? 'var(--ink)' : '',
                  fontWeight: 600, padding: '11px 0', borderRadius: 12,
                  opacity: t.disabled ? 0.5 : 1, cursor: t.disabled ? 'default' : 'pointer'
                }}
                disabled={t.disabled}
                onClick={() => { if (!t.disabled) toast(`Upgraded to ${t.n}!`); }}>
                {t.cta}
              </button>

              <div style={{borderTop: t.highlight ? '1px solid rgba(255,255,255,0.15)' : '1px solid var(--line)', paddingTop: 20}}>
                {t.features.map(f => (
                  <div key={f} style={{display:'flex', gap: 10, alignItems:'flex-start', padding:'6px 0', fontSize: 13.5, lineHeight: 1.5}}>
                    <div style={{marginTop: 3, width: 16, flexShrink: 0, color: t.highlight ? 'var(--coral-2)' : 'var(--ok)', fontWeight: 700}}>✓</div>
                    {f}
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>

        <div style={{padding: '20px 0 80px'}}>
          <h2 style={{fontFamily:'Fraunces, serif', fontSize: 32, fontWeight: 500, letterSpacing:'-0.02em', textAlign:'center', marginBottom: 24}}>
            Compare <em>every</em> feature
          </h2>
          <div style={{background:'#fff', borderRadius: 20, border:'1px solid var(--line)', overflow:'hidden'}}>
            {[
              ['Services listings', '3', 'Unlimited', 'Unlimited'],
              ['Profile photos', '6', 'Unlimited', 'Unlimited'],
              ['Custom URL', '—', '✓', '✓'],
              ['QR code', '—', '✓', '✓'],
              ['Embed widget', '—', '✓', '✓'],
              ['Analytics dashboard', '—', '✓', '✓'],
              ['Featured placement', '—', '—', '✓'],
              ['Team seats', '—', '—', '3'],
              ['Instagram auto-sync', '—', '—', '✓'],
              ['Booking fee', '5%', '3%', '2%'],
              ['Support', 'Community', 'Priority email', '24/7 chat'],
            ].map((row, i) => (
              <div key={i} style={{display:'grid', gridTemplateColumns:'2fr 1fr 1fr 1fr', padding:'14px 24px', borderTop: i > 0 ? '1px solid var(--line)' : 'none', alignItems:'center', fontSize: 14}}>
                <div style={{fontWeight: 500}}>{row[0]}</div>
                <div style={{textAlign:'center', color:'var(--muted)'}}>{row[1]}</div>
                <div style={{textAlign:'center', fontWeight: 500}}>{row[2]}</div>
                <div style={{textAlign:'center', fontWeight: 500}}>{row[3]}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

// ========== WAITLIST MODAL ==========
const WaitlistModal = ({ open, onClose, provider, toast }) => {
  if (!open) return null;
  return (
    <div className={`modal-backdrop ${open ? 'open' : ''}`} onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{maxWidth: 440, padding: 32}}>
        <div style={{width: 56, height: 56, borderRadius:'50%', background:'var(--sand-2)', display:'grid', placeItems:'center', margin:'0 auto 16px'}}>
          <Icon name="clock" size={24}/>
        </div>
        <h2 style={{fontFamily:'Fraunces, serif', fontSize: 28, fontWeight: 500, letterSpacing:'-0.02em', textAlign:'center', margin:'0 0 8px'}}>
          Fully booked through May.
        </h2>
        <p style={{color:'var(--ink-2)', textAlign:'center', fontSize: 14.5, marginBottom: 22}}>
          Join the waitlist. We'll text you the moment <strong>{provider?.name || 'Jasmine'}</strong> gets a cancellation.
        </p>
        <div className="field"><label>Your phone</label><input defaultValue="+1 (876) 555-0142"/></div>
        <div className="field"><label>Preferred service</label>
          <select style={{width:'100%', padding:'10px 12px', borderRadius: 10, border:'1px solid var(--line)', background:'#fff'}}>
            <option>Silk Press + Trim · $180</option>
            <option>Blowout · $95</option>
            <option>Deep Conditioning · $60</option>
          </select>
        </div>
        <div className="field"><label>How flexible are you?</label>
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap: 6}}>
            {['Next 7 days','Next 14 days','Any time'].map((l, i) => (
              <button key={l} className={i === 1 ? 'btn btn-primary btn-sm' : 'btn btn-outline btn-sm'}>{l}</button>
            ))}
          </div>
        </div>
        <div style={{display:'flex', gap: 8, marginTop: 22}}>
          <button className="btn btn-outline" onClick={onClose} style={{flex: 1}}>Maybe later</button>
          <button className="btn btn-brand" style={{flex: 2}} onClick={() => { toast("You're on the waitlist!"); onClose(); }}>
            Join waitlist
          </button>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { AnalyticsPage, PricingPage, WaitlistModal });
