// ========== PRODUCT CREATE/EDIT ==========
const ProductEditorPage = ({ nav, toast }) => {
  const [form, setForm] = React.useState({
    name: 'Hibiscus Hair Oil — 120ml',
    category: 'hair-care',
    shortDesc: 'Cold-pressed hibiscus-infused oil for moisture, shine, and scalp health.',
    price: 28,
    compare: 38,
    stock: 142,
    sku: 'ISL-HHO-120',
    tone: 'coral',
    tag: 'bestseller',
    sale: '-26%',
    seller: 'Island Apothecary',
  });
  const u = (k, v) => setForm({ ...form, [k]: v });

  return (
    <div className="fade-in">
      <div className="container-narrow">
        <div className="page-head">
          <div>
            <div className="eyebrow">Seller · Products</div>
            <h1>New <span className="i">product</span></h1>
          </div>
          <div style={{display:'flex', gap: 8}}>
            <button className="btn btn-outline" onClick={() => nav('seller-dashboard')}>Cancel</button>
            <button className="btn btn-ghost">Save draft</button>
            <button className="btn btn-brand" onClick={() => { toast('Product published!'); nav('seller-dashboard'); }}>
              Publish <Icon name="arrowRight" size={14}/>
            </button>
          </div>
        </div>

        <div className="editor-layout">
          <div className="editor-main">
            <h3>Photos</h3>
            <div style={{display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap: 10}}>
              {[0,1,2,3].map(i => (
                <div key={i} style={{aspectRatio: 1, borderRadius: 12, overflow:'hidden', position:'relative', border: i === 0 ? '2px solid var(--ink)' : '1px solid var(--line)'}}>
                  {i < 2 ? <Ph tone={form.tone} style={{fontSize: 10}}>photo {i+1}</Ph>
                    : <div style={{width:'100%', height:'100%', background:'var(--sand)', display:'grid', placeItems:'center', color:'var(--muted)', fontSize: 12}}>+ upload</div>}
                  {i === 0 && <div style={{position:'absolute', top: 6, left: 6, background:'var(--ink)', color:'#fff', fontSize: 10, fontWeight: 700, padding:'3px 7px', borderRadius: 999}}>COVER</div>}
                </div>
              ))}
            </div>
            <div style={{fontSize: 12, color:'var(--muted)', marginTop: 8}}>First photo is your cover. Bright, clean, product-only.</div>

            <h3>Basics</h3>
            <div className="field"><label>Name</label><input value={form.name} onChange={e => u('name', e.target.value)}/></div>
            <div className="editor-row-2">
              <div className="field"><label>Category</label>
                <select value={form.category} onChange={e => u('category', e.target.value)} style={{width:'100%', padding:'10px 12px', borderRadius: 10, border:'1px solid var(--line)', background:'#fff'}}>
                  <option value="hair-care">Hair care</option>
                  <option value="skincare">Skincare</option>
                  <option value="nails">Nails</option>
                  <option value="tools">Tools & accessories</option>
                  <option value="makeup">Makeup</option>
                </select>
              </div>
              <div className="field"><label>SKU</label><input value={form.sku} onChange={e => u('sku', e.target.value)}/></div>
            </div>
            <div className="field"><label>Short description</label>
              <textarea rows={3} value={form.shortDesc} onChange={e => u('shortDesc', e.target.value)}
                style={{width:'100%', padding:'10px 12px', borderRadius: 10, border:'1px solid var(--line)', background:'#fff', resize:'vertical', fontFamily:'inherit'}}/>
            </div>

            <h3>Pricing & stock</h3>
            <div className="editor-row-2">
              <div className="field"><label>Price (USD)</label><input type="number" value={form.price} onChange={e => u('price', +e.target.value)}/></div>
              <div className="field"><label>Compare at</label><input type="number" value={form.compare} onChange={e => u('compare', +e.target.value)}/></div>
            </div>
            <div className="editor-row-2">
              <div className="field"><label>Stock</label><input type="number" value={form.stock} onChange={e => u('stock', +e.target.value)}/></div>
              <div className="field"><label>Sale badge</label><input value={form.sale} onChange={e => u('sale', e.target.value)} placeholder="-26% or NEW"/></div>
            </div>

            <h3>Shipping</h3>
            <div className="editor-row-2">
              <div className="field"><label>Weight</label><input defaultValue="180 g"/></div>
              <div className="field"><label>Lead time</label><input defaultValue="1 business day"/></div>
            </div>
            <label style={{display:'flex', gap: 10, alignItems:'center', fontSize: 13, padding:'10px 0'}}>
              <input type="checkbox" defaultChecked/> Offer free shipping over $50
            </label>

            <h3>SEO</h3>
            <div className="field"><label>URL slug</label><input defaultValue="hibiscus-hair-oil-120ml" style={{fontFamily:'JetBrains Mono, monospace', fontSize: 13}}/></div>
            <div className="field"><label>Meta description</label>
              <textarea rows={2} defaultValue="Caribbean-grown hibiscus hair oil for deep shine and scalp health. Handcrafted in Jamaica by Island Apothecary."
                style={{width:'100%', padding:'10px 12px', borderRadius: 10, border:'1px solid var(--line)', background:'#fff', resize:'vertical', fontFamily:'inherit'}}/>
            </div>
          </div>

          <div className="editor-preview">
            <div className="preview-frame">
              <div className="lab">Storefront preview</div>
              <div style={{aspectRatio: 1, borderRadius: 12, overflow:'hidden', marginBottom: 12, position:'relative'}}>
                <Ph tone={form.tone} style={{fontSize: 10}}>{form.name.split(' ').slice(0,3).join(' ')}</Ph>
                {form.sale && <div style={{position:'absolute', top: 10, left: 10, background:'var(--coral)', color:'#fff', padding:'3px 8px', borderRadius: 999, fontSize: 10.5, fontWeight: 700}}>{form.sale}</div>}
              </div>
              <div style={{fontSize: 11.5, color:'var(--muted)'}}>{form.seller}</div>
              <div style={{fontWeight: 500, fontSize: 14.5, margin:'4px 0', lineHeight: 1.3}}>{form.name}</div>
              <div style={{display:'flex', alignItems:'baseline', gap: 8}}>
                <span style={{fontFamily:'Fraunces, serif', fontSize: 22, fontWeight: 500}}>${form.price}</span>
                {form.compare > form.price && <span style={{fontSize: 12, color:'var(--muted)', textDecoration:'line-through'}}>${form.compare}</span>}
              </div>
              <button className="btn btn-ink btn-sm" style={{width:'100%', marginTop: 12}}>Add to cart</button>
            </div>
            <div style={{fontSize: 11.5, color:'var(--muted)', marginTop: 10, textAlign:'center'}}>✓ Auto-saved just now</div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ========== AUTH: Password reset + Email verify ==========
const AuthPage = ({ nav, mode = 'reset', toast }) => {
  const [step, setStep] = React.useState(0);
  const [otp, setOtp] = React.useState(['','','','','','']);
  const inputs = React.useRef([]);

  const setOtpAt = (i, v) => {
    if (!/^\d?$/.test(v)) return;
    const next = [...otp];
    next[i] = v;
    setOtp(next);
    if (v && i < 5) inputs.current[i+1]?.focus();
  };

  if (mode === 'verify') {
    return (
      <div className="fade-in auth-layout">
        <div className="auth-side">
          <div className="eyebrow" style={{color:'var(--primary-deep)'}}>Verify email</div>
          <h1>Check your <span style={{fontStyle:'italic'}}>inbox</span>.</h1>
          <p style={{fontSize: 16, color:'var(--ink-2)', marginTop: 10, marginBottom: 28}}>
            We sent a 6-digit code to <strong>chloe@gmail.com</strong>. It expires in 10 minutes.
          </p>

          <div className="otp-row">
            {otp.map((v, i) => (
              <input key={i} ref={el => inputs.current[i] = el} className={`otp-cell ${v ? 'filled' : ''}`}
                value={v} onChange={e => setOtpAt(i, e.target.value.slice(-1))}
                maxLength={1} inputMode="numeric"/>
            ))}
          </div>

          <button className="btn btn-brand btn-lg" style={{width:'100%'}}
            disabled={otp.join('').length !== 6}
            onClick={() => { toast('Email verified! Welcome to CaribGlow.'); nav('landing'); }}>
            Verify & continue
          </button>
          <div style={{textAlign:'center', marginTop: 16, fontSize: 13, color:'var(--muted)'}}>
            Didn't get it? <span style={{color:'var(--primary-deep)', fontWeight: 500, cursor:'pointer', textDecoration:'underline'}}>Resend in 0:42</span>
          </div>
          <div style={{textAlign:'center', marginTop: 8, fontSize: 13}}>
            Wrong email? <span onClick={() => nav('landing')} style={{color:'var(--ink)', fontWeight: 500, cursor:'pointer', textDecoration:'underline'}}>Change it</span>
          </div>
        </div>
        <div className="auth-visual">
          <div style={{position:'absolute', inset: 0, display:'grid', placeItems:'center', color:'#fff', textAlign:'center', padding: 40}}>
            <div>
              <div style={{fontSize: 90, marginBottom: 20}}>✉</div>
              <div style={{fontFamily:'Fraunces, serif', fontSize: 36, fontWeight: 500, letterSpacing:'-0.02em', lineHeight: 1.1}}>
                Almost there, <em>Chloé</em>.
              </div>
              <div style={{marginTop: 14, opacity: 0.9, fontSize: 15}}>One quick check and you're in.</div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Password reset
  return (
    <div className="fade-in auth-layout">
      <div className="auth-side">
        {step === 0 && <>
          <div className="eyebrow" style={{color:'var(--primary-deep)'}}>Reset password</div>
          <h1>Forgot your <span style={{fontStyle:'italic'}}>password</span>?</h1>
          <p style={{fontSize: 16, color:'var(--ink-2)', marginTop: 10, marginBottom: 28}}>
            No worries. Enter your email and we'll send you a reset link.
          </p>
          <div className="field"><label>Email</label><input defaultValue="chloe@gmail.com" type="email"/></div>
          <button className="btn btn-brand btn-lg" style={{width:'100%', marginTop: 12}} onClick={() => setStep(1)}>
            Send reset link
          </button>
          <div style={{textAlign:'center', marginTop: 18, fontSize: 13}}>
            <span onClick={() => nav('landing')} style={{color:'var(--ink)', fontWeight: 500, cursor:'pointer'}}>← Back to sign in</span>
          </div>
        </>}
        {step === 1 && <>
          <div style={{width: 64, height: 64, borderRadius:'50%', background:'var(--sand-2)', display:'grid', placeItems:'center', marginBottom: 20}}>
            <Icon name="check" size={28} stroke={2.2}/>
          </div>
          <div className="eyebrow" style={{color:'var(--teal)'}}>Link sent</div>
          <h1>Check your <span style={{fontStyle:'italic'}}>email</span>.</h1>
          <p style={{fontSize: 16, color:'var(--ink-2)', marginTop: 10, marginBottom: 24}}>
            We sent a reset link to <strong>chloe@gmail.com</strong>. The link expires in 1 hour.
          </p>
          <div style={{background:'var(--sand)', padding: 16, borderRadius: 14, border:'1px solid var(--line)', marginBottom: 20}}>
            <div style={{fontSize: 12, color:'var(--muted)', fontWeight: 600, letterSpacing:'0.08em', textTransform:'uppercase', marginBottom: 8}}>Didn't get it?</div>
            <div style={{fontSize: 13}}>• Check your spam folder<br/>• Wait 60 seconds and try again<br/>• Make sure <em>chloe@gmail.com</em> is your registered email</div>
          </div>
          <button className="btn btn-ink btn-lg" style={{width:'100%'}} onClick={() => setStep(2)}>Open email (demo)</button>
        </>}
        {step === 2 && <>
          <div className="eyebrow" style={{color:'var(--primary-deep)'}}>New password</div>
          <h1>Create a <span style={{fontStyle:'italic'}}>strong</span> one.</h1>
          <p style={{fontSize: 16, color:'var(--ink-2)', marginTop: 10, marginBottom: 24}}>
            At least 10 characters, with a number and symbol.
          </p>
          <div className="field"><label>New password</label><input type="password" defaultValue="Glowup2026!"/></div>
          <div className="field"><label>Confirm password</label><input type="password" defaultValue="Glowup2026!"/></div>
          <div style={{display:'flex', gap: 4, margin:'4px 0 8px'}}>
            {[0,1,2,3].map(i => <div key={i} style={{flex: 1, height: 4, borderRadius: 2, background: i < 4 ? 'var(--ok)' : 'var(--line)'}}/>)}
          </div>
          <div style={{fontSize: 12, color:'var(--ok)', fontWeight: 500, marginBottom: 20}}>✓ Strong password</div>
          <button className="btn btn-brand btn-lg" style={{width:'100%'}}
            onClick={() => { toast('Password updated!'); nav('landing'); }}>
            Save & sign in
          </button>
        </>}
      </div>
      <div className="auth-visual">
        <div style={{position:'absolute', inset: 0, display:'grid', placeItems:'center', color:'#fff', textAlign:'center', padding: 40}}>
          <div>
            <div style={{fontSize: 90, marginBottom: 20}}>✦</div>
            <div style={{fontFamily:'Fraunces, serif', fontSize: 36, fontWeight: 500, letterSpacing:'-0.02em', lineHeight: 1.1}}>
              Your glow,<br/><em>secured.</em>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ========== PUBLIC PROVIDER BOOKING (bio-link mode) ==========
const PublicBookingPage = ({ nav, openBooking }) => {
  const p = PROVIDERS[0]; // Jasmine
  const services = [
    { name: 'Silk Press + Trim', d: '2h 30m', price: 180, desc: 'Signature service.' },
    { name: 'Deep Conditioning', d: '1h', price: 60, desc: 'Add-on or standalone.' },
    { name: 'Blowout', d: '1h 15m', price: 95, desc: 'Big, bouncy volume.' },
  ];
  return (
    <div className="fade-in" style={{background:'var(--sand)', minHeight: 'calc(100vh - 70px)', padding: '0 20px 60px'}}>
      <div style={{maxWidth: 460, margin:'0 auto', paddingTop: 28}}>
        <div style={{textAlign:'center', marginBottom: 20}}>
          <div style={{width: 96, height: 96, borderRadius:'50%', margin:'0 auto 14px', overflow:'hidden', border:'4px solid #fff', boxShadow: 'var(--shadow-lg)'}}>
            <Ph tone={p.tone} style={{fontSize: 11}}>{p.name}</Ph>
          </div>
          <div style={{fontFamily:'Fraunces, serif', fontSize: 28, fontWeight: 500, letterSpacing:'-0.02em'}}>
            {p.name} {p.verified && <Icon name="verified" size={18}/>}
          </div>
          <div style={{fontSize: 13.5, color:'var(--muted)', marginTop: 4}}>{p.tagline} · {p.area}</div>
          <div style={{display:'flex', justifyContent:'center', gap: 14, marginTop: 12, fontSize: 13}}>
            <span><Icon name="star" size={12}/> <strong>{p.rating}</strong> ({p.reviews})</span>
            <span style={{color:'var(--muted)'}}>·</span>
            <span>{p.joinedYear === 2023 ? '2 yrs on CaribGlow' : 'Verified pro'}</span>
          </div>
        </div>

        <div style={{display:'flex', gap: 8, justifyContent:'center', marginBottom: 22}}>
          {['Instagram','TikTok','WhatsApp'].map(s => (
            <div key={s} style={{fontSize: 11.5, color:'var(--muted)', padding:'5px 10px', background:'#fff', border:'1px solid var(--line)', borderRadius: 999}}>{s}</div>
          ))}
        </div>

        <div style={{marginBottom: 14, fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform:'uppercase', color:'var(--muted)', textAlign:'center'}}>
          Book a service
        </div>
        {services.map(s => (
          <div key={s.name} style={{background:'#fff', borderRadius: 16, padding: '16px 18px', marginBottom: 10, border:'1px solid var(--line)', display:'flex', justifyContent:'space-between', alignItems:'center', gap: 14}}>
            <div style={{flex: 1, minWidth: 0}}>
              <div style={{fontWeight: 600, fontSize: 14.5}}>{s.name}</div>
              <div style={{fontSize: 12, color:'var(--muted)', marginTop: 3}}>{s.d} · {s.desc}</div>
            </div>
            <div style={{textAlign:'right'}}>
              <div style={{fontFamily:'Fraunces, serif', fontSize: 20, fontWeight: 500}}>${s.price}</div>
              <button className="btn btn-ink btn-sm" style={{marginTop: 4}}
                onClick={() => openBooking(p, { ...s, id: s.name })}>Book</button>
            </div>
          </div>
        ))}

        <div style={{marginTop: 22, display:'grid', gridTemplateColumns:'1fr 1fr', gap: 8}}>
          <button className="btn btn-outline" onClick={() => nav('messages')}><Icon name="msg" size={13}/> Message</button>
          <button className="btn btn-outline" onClick={() => nav('provider-profile')}>Full profile</button>
        </div>

        <div style={{marginTop: 32, textAlign:'center', fontSize: 11, color:'var(--muted)'}}>
          Powered by <strong style={{color:'var(--ink)'}}>CaribGlow</strong> · glowcarib.com/{p.username}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { ProductEditorPage, AuthPage, PublicBookingPage });
