// Overlays: cart drawer, search, quiz, chatbot, search modal

const StarRow = ({ rating, size = 12 }) => (
  <span style={{ display: 'inline-flex', gap: 1, color: 'var(--gold)' }}>
    {[1,2,3,4,5].map(i => <window.Icon key={i} name={i <= Math.round(rating) ? 'starFill' : 'star'} size={size}/>)}
  </span>
);

function CartDrawer({ open, onClose, items, updateQty, removeItem, goto }) {
  const [closing, setClosing] = React.useState(false);
  const close = () => { setClosing(true); setTimeout(() => { setClosing(false); onClose(); }, 280); };
  if (!open) return null;
  const subtotal = items.reduce((s, i) => s + i.price * i.qty, 0);
  const shipping = subtotal > 999 ? 0 : 80;
  return (
    <>
      <div className="drawer-back" onClick={close} style={{ animation: closing ? 'fadeOut 0.28s forwards' : 'fadeIn 0.2s' }}/>
      <aside className="drawer" style={{ animation: closing ? 'slideRightOut 0.28s cubic-bezier(0.4,0,1,1) forwards' : 'slideRight 0.3s' }}>
        <div className="between" style={{ padding: '20px 24px', borderBottom: '1px solid var(--line-soft)' }}>
          <div>
            <div className="mono" style={{ color: 'var(--muted)' }}>Your basket</div>
            <div style={{ fontSize: 22, fontWeight: 500, letterSpacing: '-0.02em', marginTop: 4 }}>{items.length} {items.length === 1 ? 'item' : 'items'}</div>
          </div>
          <button onClick={close} className="round-btn" style={{ width: 36, height: 36, borderRadius: 999, border: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><window.Icon name="close" size={16}/></button>
        </div>

        {items.length === 0 ? (
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 32, gap: 16 }}>
            <div className="ph" style={{ width: 100, height: 100, borderRadius: 999 }}>empty</div>
            <div style={{ fontSize: 18, fontWeight: 500 }}>Your basket is empty</div>
            <button className="btn btn-primary" onClick={() => { onClose(); goto('Shop'); }}>Browse pastes</button>
          </div>
        ) : (
          <>
            <div style={{ flex: 1, overflowY: 'auto', padding: '8px 24px' }}>
              {items.map((it, i) => (
                <div key={it.id} className="cart-item-in" style={{ display: 'flex', gap: 14, padding: '20px 0', borderBottom: '1px solid var(--line-soft)', animationDelay: `${200 + i * 60}ms` }}>
                  {it.img
                    ? <img src={window.imgSrc(it.img)} alt={it.name} style={{ width: 84, height: 100, objectFit: 'cover', borderRadius: 6, flexShrink: 0, display: 'block' }}/>
                    : <div className="ph product" style={{ width: 84, height: 100, flexShrink: 0 }}>{it.name}</div>
                  }
                  <div style={{ flex: 1 }}>
                    <div className="between">
                      <div>
                        <div style={{ fontSize: 14, fontWeight: 500 }}>{it.name}</div>
                        <div className="mono" style={{ color: 'var(--muted)', marginTop: 4 }}>{it.weight}{it.sub ? ' · subscribe' : ''}</div>
                      </div>
                      <button onClick={() => removeItem(it.id)} style={{ color: 'var(--muted)' }}><window.Icon name="close" size={14}/></button>
                    </div>
                    <div className="between" style={{ marginTop: 14 }}>
                      <div style={{ display: 'flex', alignItems: 'center', border: '1px solid var(--line)', borderRadius: 999 }}>
                        <button onClick={() => updateQty(it.id, Math.max(1, it.qty - 1))} className="round-btn" style={{ padding: '6px 10px' }}><window.Icon name="minus" size={12}/></button>
                        <span style={{ padding: '0 8px', fontSize: 13, fontFamily: 'var(--font-mono)' }}>{it.qty}</span>
                        <button onClick={() => updateQty(it.id, it.qty + 1)} className="round-btn" style={{ padding: '6px 10px' }}><window.Icon name="plus" size={12}/></button>
                      </div>
                      <div style={{ fontSize: 15, fontWeight: 500 }}>₹{(it.price * it.qty).toLocaleString('en-IN')}</div>
                    </div>
                  </div>
                </div>
              ))}

              <div style={{ background: 'var(--surface)', border: '1px solid var(--line-soft)', borderRadius: 8, padding: 16, marginTop: 16 }}>
                <div className="mono" style={{ color: 'var(--accent)', marginBottom: 6 }}>You're ₹{Math.max(0, 1500 - subtotal)} away from a free amla shot</div>
                <div style={{ height: 4, background: 'var(--line-soft)', borderRadius: 4, overflow: 'hidden' }}>
                  <div style={{ height: '100%', width: `${Math.min(100, subtotal/1500*100)}%`, background: 'var(--accent)', transition: 'width 0.3s' }}/>
                </div>
              </div>
            </div>

            <div style={{ padding: '20px 24px', borderTop: '1px solid var(--line-soft)' }}>
              <div className="between" style={{ marginBottom: 6 }}><span style={{ color: 'var(--muted)', fontSize: 13 }}>Subtotal</span><span style={{ fontWeight: 500 }}>₹{subtotal.toLocaleString('en-IN')}</span></div>
              <div className="between" style={{ marginBottom: 12 }}><span style={{ color: 'var(--muted)', fontSize: 13 }}>Shipping</span><span style={{ fontWeight: 500 }}>{shipping === 0 ? 'Free' : `₹${shipping}`}</span></div>
              <div className="between" style={{ paddingTop: 12, borderTop: '1px solid var(--line-soft)', marginBottom: 16 }}>
                <span style={{ fontWeight: 500 }}>Total</span>
                <span style={{ fontSize: 22, fontWeight: 500, letterSpacing: '-0.02em' }}>₹{(subtotal + shipping).toLocaleString('en-IN')}</span>
              </div>
              <button className="btn btn-primary" style={{ width: '100%' }} onClick={() => { onClose(); goto('Checkout'); }}>Checkout <window.Icon name="arrR" size={14}/></button>
              <button className="btn btn-ghost" style={{ width: '100%', marginTop: 8 }} onClick={() => { onClose(); goto('Cart'); }}>View full cart</button>
            </div>
          </>
        )}
      </aside>
    </>
  );
};

function SearchModal({ open, onClose, goto }) {
  const [q, setQ] = React.useState('');
  const [closing, setClosing] = React.useState(false);
  const close = () => { setClosing(true); setTimeout(() => { setClosing(false); onClose(); }, 250); };
  if (!open) return null;
  const suggestions = ['Muejaza For Men', 'Shahi Kalp', 'Kashmiri Shilajit', 'Testo Vardhak', 'Muejaza Plus'];
  return (
    <div className="modal-back" onClick={close} style={{ animation: closing ? 'fadeOut 0.25s forwards' : 'fadeIn 0.2s' }}>
      <div onClick={e => e.stopPropagation()} style={{ width: 'min(640px, 100%)', background: 'var(--bg)', borderRadius: 16, padding: 24, animation: closing ? 'slideUpOut 0.25s forwards' : 'slideUp 0.25s' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, borderBottom: '1px solid var(--line)', paddingBottom: 14 }}>
          <window.Icon name="search" size={20}/>
          <input autoFocus value={q} onChange={e => setQ(e.target.value)} placeholder="Search pastes, ingredients, concerns..." style={{ flex: 1, background: 'transparent', border: 'none', outline: 'none', fontSize: 18, color: 'var(--ink)' }}/>
          <button onClick={close} className="mono" style={{ color: 'var(--muted)' }}>ESC</button>
        </div>
        <div style={{ marginTop: 20 }}>
          <div className="mono" style={{ color: 'var(--muted)', marginBottom: 12 }}>Popular</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {suggestions.map(s => (
              <button key={s} onClick={() => { setQ(s); goto('Shop'); onClose(); }} className="badge">{s}</button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

// Find-my-formula quiz
const QUIZ = [
  { q: 'What is your primary goal?', opts: [
    { l: 'Boost energy & stamina', tag: 'energy' },
    { l: 'Improve immunity', tag: 'immunity' },
    { l: 'Better sleep & less stress', tag: 'sleep' },
    { l: 'Overall vitality & strength', tag: 'vitality' },
  ]},
  { q: 'Who is this for?', opts: [
    { l: 'For me — men\'s health', tag: 'men' },
    { l: 'For me — women\'s health', tag: 'women' },
    { l: 'For both of us', tag: 'couple' },
    { l: 'Looking for best quality', tag: 'premium' },
  ]},
  { q: 'How committed are you?', opts: [
    { l: 'Curious — want to try', tag: 'starter' },
    { l: 'Ready for a full routine', tag: 'classic' },
    { l: 'Want the absolute best', tag: 'premium' },
    { l: 'Great value matters', tag: 'value' },
  ]},
  { q: 'Any preference?', opts: [
    { l: 'Just the purest Shilajit', tag: 'shilajit' },
    { l: 'Multi-herb formula', tag: 'formula' },
    { l: 'Bundle & save more', tag: 'bundle' },
    { l: 'No preference', tag: 'classic' },
  ]},
];

function QuizModal({ open, onClose, goto, addToCart }) {
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState([]);
  const [closing, setClosing] = React.useState(false);
  const close = () => { setClosing(true); setTimeout(() => { setClosing(false); onClose(); }, 250); };
  React.useEffect(() => { if (open) { setStep(0); setAnswers([]); setClosing(false); } }, [open]);
  if (!open) return null;

  const done = step >= QUIZ.length;

  const pick = () => {
    const tags = answers;
    if (tags.includes('bundle') || tags.includes('couple')) return window.PRODUCTS.find(p => p.id === 'muejaza-shahi-kalp-combo');
    if (tags.includes('premium')) return window.PRODUCTS.find(p => p.id === 'muejaza-plus');
    if (tags.includes('shilajit')) return window.PRODUCTS.find(p => p.id === 'kashmiri-shilajit');
    if (tags.includes('women')) return window.PRODUCTS.find(p => p.id === 'shahi-kalp');
    if (tags.includes('sleep') || tags.includes('immunity')) return window.PRODUCTS.find(p => p.id === 'shahi-kalp');
    if (tags.includes('energy') || tags.includes('vitality')) return window.PRODUCTS.find(p => p.id === 'testo-vardhak');
    return window.PRODUCTS.find(p => p.id === 'muejaza-for-men');
  };

  const getReasons = (tags) => {
    const reasons = [];
    if (tags.includes('energy') || tags.includes('vitality')) reasons.push('Supports daily energy & stamina');
    if (tags.includes('immunity')) reasons.push('Strengthens natural immunity');
    if (tags.includes('sleep')) reasons.push('Promotes restful sleep');
    if (tags.includes('premium')) reasons.push('Our most potent formulation');
    if (tags.includes('shilajit')) reasons.push('Purest Himalayan resin, 70% Fulvic Acid');
    if (tags.includes('bundle')) reasons.push('Best value for couples & families');
    return reasons.length ? reasons : ['Broad-spectrum daily wellness', 'Cold-processed, 40+ herbs'];
  };

  const rec = done ? pick() : null;
  const reasons = done ? getReasons(answers) : [];

  return (
    <div className="modal-back" onClick={close} style={{ animation: closing ? 'fadeOut 0.25s forwards' : 'fadeIn 0.2s' }}>
      <div onClick={e => e.stopPropagation()} style={{ width: 'min(680px, 100%)', maxHeight: '90vh', background: 'var(--bg)', borderRadius: 20, padding: 0, animation: closing ? 'slideUpOut 0.25s forwards' : 'slideUp 0.3s', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '20px 28px', borderBottom: '1px solid var(--line-soft)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0 }}>
          <div className="mono" style={{ color: 'var(--muted)' }}>Find my formula · {done ? 'your match' : `${step+1}/${QUIZ.length}`}</div>
          <button onClick={close}><window.Icon name="close" size={18}/></button>
        </div>

        <div style={{ height: 3, background: 'var(--line-soft)', flexShrink: 0 }}>
          <div style={{ height: '100%', width: `${(done ? QUIZ.length : step) / QUIZ.length * 100}%`, background: 'var(--primary)', transition: 'width 0.4s cubic-bezier(0.22,1,0.36,1)' }}/>
        </div>

        <div style={{ padding: '36px 32px', overflowY: 'auto' }}>
          {!done ? (
            <>
              <h3 style={{ fontSize: 28, fontWeight: 500, letterSpacing: '-0.03em', marginBottom: 24, textWrap: 'pretty' }}>{QUIZ[step].q}</h3>
              <div className="col gap-3">
                {QUIZ[step].opts.map(o => (
                  <button key={o.l} onClick={() => { setAnswers([...answers, o.tag]); setStep(step + 1); }}
                    className="quiz-option"
                    style={{ textAlign: 'left', padding: '18px 20px', border: '1px solid var(--line)', borderRadius: 12, fontSize: 16, transition: 'all 0.18s', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}
                    onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--ink)'; e.currentTarget.style.background = 'var(--surface)'; }}
                    onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--line)'; e.currentTarget.style.background = 'transparent'; }}>
                    {o.l} <span className="quiz-arrow"><window.Icon name="arrR" size={16}/></span>
                  </button>
                ))}
              </div>
              {step > 0 && <button onClick={() => setStep(step - 1)} className="mono" style={{ marginTop: 20, color: 'var(--muted)' }}>← back</button>}
            </>
          ) : rec ? (
            <div style={{ animation: 'fadeInUp 0.4s cubic-bezier(0.22,1,0.36,1)' }}>
              <div className="mono" style={{ color: 'var(--accent)', marginBottom: 8 }}>Your perfect match</div>
              <h3 style={{ fontSize: 32, fontWeight: 500, letterSpacing: '-0.035em', lineHeight: 1.05, marginBottom: 4 }}>{rec.name}</h3>
              <p style={{ color: 'var(--muted)', fontSize: 14, marginBottom: 20 }}>{rec.tagline}</p>

              <div style={{ display: 'flex', gap: 16, padding: 20, background: 'var(--surface)', borderRadius: 12, marginBottom: 20, border: '1px solid var(--line-soft)' }}>
                <div className="ph product" style={{ width: 90, height: 112, flexShrink: 0, borderRadius: 8 }}>{rec.name}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 26, fontWeight: 500, letterSpacing: '-0.02em', marginBottom: 4 }}>₹{rec.price.toLocaleString('en-IN')}</div>
                  <div className="mono" style={{ color: 'var(--muted)', marginBottom: 12, fontSize: 10 }}>MRP ₹{rec.mrp} · incl. taxes</div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                    {rec.hero.slice(0,3).map(h => <span key={h} className="badge">{h}</span>)}
                  </div>
                </div>
              </div>

              <div style={{ marginBottom: 24 }}>
                <div className="mono" style={{ color: 'var(--muted)', marginBottom: 10 }}>Why this formula for you</div>
                {reasons.map((r, i) => (
                  <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', marginBottom: 8 }}>
                    <window.Icon name="check" size={14} style={{ color: 'var(--primary)', marginTop: 2 }}/>
                    <span style={{ fontSize: 14, color: 'var(--ink-2)' }}>{r}</span>
                  </div>
                ))}
              </div>

              <div style={{ display: 'flex', gap: 10, marginBottom: 12 }}>
                <button className="btn btn-primary" style={{ flex: 1 }} onClick={() => { addToCart(rec); onClose(); }}>
                  Add to basket — ₹{rec.price.toLocaleString('en-IN')}
                </button>
                <button className="btn btn-ghost" onClick={() => { goto('Product', rec.id); onClose(); }}>
                  View details
                </button>
              </div>
              <button onClick={() => { setStep(0); setAnswers([]); }} className="mono" style={{ color: 'var(--muted)', fontSize: 11 }}>↺ retake quiz</button>
            </div>
          ) : null}
        </div>
      </div>
    </div>
  );
};

// AI Chatbot
function Chatbot({ open, onClose }) {
  const [messages, setMessages] = React.useState([
    { role: 'bot', text: 'Namaste 🙏 I\'m Vaidya, your nkherbal guide. Ask me anything — ingredients, doses, sourcing, or which paste fits your routine.' },
  ]);
  const [input, setInput] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const listRef = React.useRef();

  React.useEffect(() => {
    if (listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight;
  }, [messages, loading]);

  const send = async () => {
    if (!input.trim()) return;
    const userMsg = input.trim();
    setMessages(m => [...m, { role: 'user', text: userMsg }]);
    setInput('');
    setLoading(true);
    try {
      const system = `You are Vaidya, the helpful AI consultant for nkherbal — a premium Ayurvedic brand specializing in slow-cooked chyawanprash and herbal pastes. Be warm, concise, knowledgeable. Recommend specific nkherbal products when relevant: Classic Chyawanprash (₹890, immunity), Sugar-Free (₹1090, diabetic-friendly), Kids (₹690, ages 3+), Gold (₹2890, premium with swarna bhasma), Nidra Paste (₹990, sleep), Saundarya Paste (₹1190, skin/hair). Keep replies under 80 words. Use plain text, no markdown.`;
      const reply = await window.claude.complete({
        messages: [
          { role: 'user', content: `${system}\n\nUser: ${userMsg}` },
        ],
      });
      setMessages(m => [...m, { role: 'bot', text: reply }]);
    } catch (e) {
      setMessages(m => [...m, { role: 'bot', text: 'Sorry — I\'m having trouble reaching the herb garden. Try again in a moment, or write to care@nkherbal.com.' }]);
    } finally {
      setLoading(false);
    }
  };

  if (!open) return null;
  return (
    <div style={{ position: 'fixed', bottom: 24, right: 24, width: 'min(380px, calc(100vw - 32px))', height: 'min(560px, calc(100vh - 100px))', background: 'var(--bg)', borderRadius: 16, boxShadow: '0 20px 60px rgba(0,0,0,0.25)', border: '1px solid var(--line)', display: 'flex', flexDirection: 'column', zIndex: 750, animation: 'slideUp 0.25s' }}>
      <div className="between" style={{ padding: '16px 18px', borderBottom: '1px solid var(--line-soft)' }}>
        <div>
          <div style={{ fontSize: 15, fontWeight: 500 }}>Vaidya · AI guide</div>
          <div className="mono" style={{ color: 'var(--muted)', display: 'flex', alignItems: 'center', gap: 6, marginTop: 3 }}><span style={{ width: 6, height: 6, borderRadius: 999, background: '#3b9b3b' }}/>online</div>
        </div>
        <button onClick={onClose}><window.Icon name="close" size={16}/></button>
      </div>
      <div ref={listRef} style={{ flex: 1, overflowY: 'auto', padding: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {messages.map((m, i) => (
          <div key={i} style={{ display: 'flex', justifyContent: m.role === 'user' ? 'flex-end' : 'flex-start' }}>
            <div style={{ maxWidth: '85%', padding: '10px 14px', borderRadius: 14, fontSize: 14, lineHeight: 1.45, background: m.role === 'user' ? 'var(--ink)' : 'var(--surface)', color: m.role === 'user' ? 'var(--bg)' : 'var(--ink)', border: m.role === 'bot' ? '1px solid var(--line-soft)' : 'none' }}>{m.text}</div>
          </div>
        ))}
        {loading && <div style={{ padding: '10px 14px', background: 'var(--surface)', border: '1px solid var(--line-soft)', borderRadius: 14, alignSelf: 'flex-start' }}><span className="dot-load"><span></span><span></span><span></span></span></div>}
      </div>
      <div style={{ padding: 12, borderTop: '1px solid var(--line-soft)', display: 'flex', gap: 8 }}>
        <input value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => e.key === 'Enter' && send()} placeholder="Ask about a remedy..." style={{ flex: 1, padding: '10px 14px', borderRadius: 999, border: '1px solid var(--line)', background: 'var(--surface)', fontSize: 13, outline: 'none' }}/>
        <button onClick={send} disabled={!input.trim() || loading} style={{ width: 38, height: 38, borderRadius: 999, background: 'var(--ink)', color: 'var(--bg)', display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: input.trim() && !loading ? 1 : 0.4 }}><window.Icon name="arrR" size={14}/></button>
      </div>
    </div>
  );
};

window.StarRow = StarRow;
window.CartDrawer = CartDrawer;
window.SearchModal = SearchModal;
window.QuizModal = QuizModal;
window.Chatbot = Chatbot;
