/* ─── Seller Panel — shared chrome: Sidebar + Topbar + Page header ─────────
   Every screen renders inside <AppShell title=… action=… nav=… onNav=…> so the
   layout is consistent and the brand visuals live in exactly one place. */

/* Brand logo — uses the real PNG asset so it matches the production mark */
const Logo = ({ size = 32, white = false, className = '' }) => (
  <img src={white ? "branded/assets/logo-white.png" : "branded/assets/logo-black.png"}
       alt="Review Buddie"
       className={"select-none " + className}
       style={{ height: size, width: 'auto' }}/>
);

/* Pixel icons for the sidebar */
const NavIcons = {
  dashboard: (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <rect x="3"  y="3"  width="7" height="7" rx="1.5"/>
      <rect x="14" y="3"  width="7" height="7" rx="1.5"/>
      <rect x="3"  y="14" width="7" height="7" rx="1.5"/>
      <rect x="14" y="14" width="7" height="7" rx="1.5"/>
    </svg>
  ),
  analytics: (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M3 3v16a2 2 0 0 0 2 2h16"/>
      <path d="M7 15l4-5 3 3 5-7" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  ),
  product: (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M21 16V8a2 2 0 0 0-1-1.7l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.7l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>
      <path d="M3.3 7L12 12l8.7-5M12 22V12"/>
    </svg>
  ),
  promotion: (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M20.6 13.4l-7.7 7.7a2 2 0 0 1-2.8 0L2 12.8V3h9.8l8.8 8.8a2 2 0 0 1 0 2.6z"/>
      <circle cx="7" cy="8" r="1.6" fill="currentColor"/>
    </svg>
  ),
  campaign: (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M3 11v2a2 2 0 0 0 2 2h1l5 4V5L6 9H5a2 2 0 0 0-2 2z"/>
      <path d="M16 8a5 5 0 0 1 0 8M19 5a9 9 0 0 1 0 14"/>
    </svg>
  ),
  inbox: (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M22 12h-6l-2 3h-4l-2-3H2"/>
      <path d="M5.45 5.11L2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/>
    </svg>
  ),
  inserts: (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <rect x="3"  y="3" width="7" height="7" rx="1"/>
      <rect x="14" y="3" width="7" height="7" rx="1"/>
      <rect x="3"  y="14" width="7" height="7" rx="1"/>
      <path d="M14 14h7M14 18h7M14 22h4"/>
    </svg>
  ),
  customers: (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <circle cx="12" cy="8" r="4"/>
      <path d="M4 21a8 8 0 0 1 16 0"/>
    </svg>
  ),
  book: (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/>
    </svg>
  ),
  gift: (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M20 12v9H4v-9M2 7h20v5H2zM12 7v14M12 7s-1.5-4-4.5-4A2.5 2.5 0 0 0 7 7.5"/>
      <path d="M12 7s1.5-4 4.5-4A2.5 2.5 0 0 1 17 7.5"/>
    </svg>
  ),
  settings: (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <circle cx="12" cy="12" r="3"/>
      <path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1 1.7 1.7 0 0 0-.3-1.8l-.1-.1A2 2 0 1 1 7 4.4l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/>
    </svg>
  ),
  logout: (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
      <path d="M16 17l5-5-5-5M21 12H9"/>
    </svg>
  ),
};

const NAV = [
  { id:'dashboard', label:'Dashboard',       icon:'dashboard' },
  { id:'products',  label:'Products',        icon:'product',   step:1 },
  { id:'promotions',label:'Promotions',      icon:'promotion', step:2 },
  { id:'campaigns', label:'Campaigns',       icon:'campaign',  step:3 },
  { id:'claims',    label:'Claim Center',    icon:'inbox',     needs:'ClaimCenter' },
  { id:'customers', label:'Customers',       icon:'customers' },
  { id:'referrals', label:'Refer & Earn',    icon:'gift',      needs:'ReferEarn' },
  { id:'knowledge', label:'Knowledge Center', icon:'book',     needs:'KnowledgeCenter' },
];

function Sidebar({ active, onNav }) {
  const isSettings = active === 'settings';
  const items = NAV.filter(n => !n.needs || window[n.needs]);
  const itemCls = (on) =>
    "group w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-[14px] font-medium transition-all duration-150 " +
    (on
      ? "bg-white/[0.07] text-white shadow-[inset_0_0_0_1px_rgba(255,255,255,0.08)]"
      : "text-white/55 hover:text-white hover:bg-white/[0.04]");
  return (
    <aside className="w-[244px] shrink-0 flex flex-col h-screen sticky top-0"
           style={{backgroundColor:'var(--sidebar-bg, #0E1A24)', backgroundImage:'radial-gradient(120% 60% at 0% 0%, rgba(14,154,214,0.16), transparent 60%)'}}>
      {/* logo */}
      <button onClick={() => onNav('dashboard')} className="px-5 pt-6 pb-5 text-left">
        <Logo white size={30}/>
      </button>

      {/* primary nav */}
      <nav className="flex-1 px-3.5 overflow-y-auto no-scrollbar">
        <p className="px-3 pt-2 pb-2 text-[10.5px] font-bold uppercase tracking-[0.14em] text-white/30">Menu</p>
        <div className="space-y-1">
          {items.filter(n=>!n.step).slice(0,1).map(item => {
            const isActive = active === item.id;
            return (
              <button key={item.id} onClick={() => onNav(item.id)} className={itemCls(isActive)}>
                <span className={"shrink-0 transition-colors " + (isActive ? "acc-text" : "text-current")}>{NavIcons[item.icon]}</span>
                <span className="flex-1 text-left">{item.label}</span>
                {isActive && <span className="w-1.5 h-1.5 rounded-full acc-bg"></span>}
              </button>
            );
          })}
        </div>
        <p className="px-3 pt-5 pb-2 text-[10.5px] font-bold uppercase tracking-[0.14em] text-white/30">Set up in 3 steps</p>
        <div className="space-y-1">
          {items.filter(n=>n.step).map(item => {
            const isActive = active === item.id;
            return (
              <button key={item.id} onClick={() => onNav(item.id)} className={itemCls(isActive)}>
                <span className={"shrink-0 transition-colors " + (isActive ? "acc-text" : "text-current")}>{NavIcons[item.icon]}</span>
                <span className="flex-1 text-left">{item.label}</span>
                <span className={"w-5 h-5 rounded-full text-[10px] font-bold flex items-center justify-center transition-colors " + (isActive ? "acc-bg text-white" : "bg-white/10 text-white/50")}>{item.step}</span>
              </button>
            );
          })}
        </div>
        <p className="px-3 pt-5 pb-2 text-[10.5px] font-bold uppercase tracking-[0.14em] text-white/30">Manage</p>
        <div className="space-y-1">
          {items.filter(n=>!n.step).slice(1).map(item => {
            const isActive = active === item.id;
            return (
              <button key={item.id} onClick={() => onNav(item.id)} className={itemCls(isActive)}>
                <span className={"shrink-0 transition-colors " + (isActive ? "acc-text" : "text-current")}>{NavIcons[item.icon]}</span>
                <span className="flex-1 text-left">{item.label}</span>
                {isActive && <span className="w-1.5 h-1.5 rounded-full acc-bg"></span>}
              </button>
            );
          })}
        </div>
      </nav>

      {/* upgrade nudge */}
      <div className="px-3.5 pb-3">
        <div className="rounded-2xl p-4 text-white relative overflow-hidden"
             style={{background:'linear-gradient(150deg, var(--accent), var(--accent-dark))'}}>
          <p className="text-[13px] font-bold leading-tight">Unlock more reviews</p>
          <p className="text-[11.5px] text-white/75 mt-1 leading-snug">You've used 8 of 10 on the Free plan.</p>
          <button onClick={() => window.__openPricing ? window.__openPricing() : onNav('settings','billing')}
                  className="mt-3 w-full bg-white text-[12.5px] font-bold py-2 rounded-lg acc-text hover:bg-white/90 transition">
            Upgrade plan
          </button>
        </div>
      </div>

      {/* help + settings + logout */}
      <div className="px-3.5 pb-5 pt-3 border-t border-white/[0.07] space-y-1">
        <button onClick={() => window.__openHelp && window.__openHelp()} className={itemCls(false)}>
          <span className="shrink-0"><svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><circle cx="12" cy="12" r="9"></circle><path d="M9.2 9a2.8 2.8 0 0 1 5.5.7c0 1.8-2.7 2.3-2.7 3.8" strokeLinecap="round"></path><circle cx="12" cy="17" r="0.5" fill="currentColor"></circle></svg></span><span className="whitespace-nowrap">Help &amp; Support</span>
        </button>
        <button onClick={() => onNav('settings')} className={itemCls(isSettings)}>
          <span className="shrink-0">{NavIcons.settings}</span>Settings
        </button>
        <button onClick={() => window.rbToast ? window.rbToast('Logged out (demo)') : alert('Logged out (demo)')}
          className="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-[14px] font-medium text-white/55 hover:text-white hover:bg-white/[0.04] transition-all">
          <span className="shrink-0">{NavIcons.logout}</span>Logout
        </button>
      </div>
    </aside>
  );
}

/* Help & Support — seller files a ticket; it lands in the Admin Portal support inbox */
function HelpSupport() {
  const [open, setOpen] = React.useState(false);
  const [sent, setSent] = React.useState(false);
  const [cat, setCat] = React.useState('Payouts & rewards');
  const [msg, setMsg] = React.useState('');
  const [chat, setChat] = React.useState(false);
  const [chatMsgs, setChatMsgs] = React.useState([]);
  const [chatDraft, setChatDraft] = React.useState('');
  const [typing, setTyping] = React.useState(false);
  React.useEffect(() => { window.__openHelp = () => setOpen(true); return () => { delete window.__openHelp; }; }, []);
  const close = () => { setOpen(false); setTimeout(()=>{ setSent(false); setMsg(''); setChat(false); setChatMsgs([]); setChatDraft(''); setTyping(false); }, 300); };
  const openAdminInbox = () => { try { localStorage.setItem('rb-admin-route','support'); } catch(e){} window.open('Admin Portal.html','_blank'); };
  const chatSend = () => {
    const t = chatDraft.trim(); if(!t) return;
    setChatMsgs(m=>[...m,{from:'me',txt:t}]); setChatDraft(''); setTyping(true);
    setTimeout(()=>{ setTyping(false); setChatMsgs(m=>[...m,{from:'agent',txt:m.length<2 ? "Thanks for the details — let me pull up your account. One moment." : "I've flagged this to the right team and left a note on your account — you'll see an update in your inbox shortly. Anything else?"}]); }, 1400);
  };
  if (!open) return null;
  return ReactDOM.createPortal(
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-ink/40 p-4" onClick={close}>
      <div className="bg-white rounded-3xl shadow-pop p-7 w-full max-w-[440px]" onClick={e=>e.stopPropagation()}>
        {chat ? (
          <div className="flex flex-col" style={{height:'440px'}}>
            <div className="flex items-center gap-3 pb-4 border-b border-line">
              <span className="relative w-10 h-10 rounded-full bg-surface-subtle border border-line flex items-center justify-center text-[14px] font-extrabold acc-text">R<span className="absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full bg-green-500 border-2 border-white"></span></span>
              <div className="flex-1 min-w-0">
                <p className="text-[14px] font-extrabold text-ink">Riya · Live support</p>
                <p className="text-[11.5px] text-green-600 font-bold">Online · replies in ~1 min</p>
              </div>
              <button onClick={()=>setChat(false)} className="text-[12px] font-bold text-ink-muted hover:text-ink transition-colors">← Back</button>
            </div>
            <div className="flex-1 overflow-y-auto py-4 space-y-2.5">
              <div className="max-w-[85%] rounded-2xl rounded-tl-md px-4 py-2.5 bg-surface-subtle border border-line/70 text-[13px] text-ink leading-relaxed">Hi! I'm Riya from ReviewBuddie support. What can I help you with today?</div>
              {chatMsgs.map((m,i)=>(
                m.from==='me'
                  ? <div key={i} className="max-w-[85%] ml-auto rounded-2xl rounded-tr-md px-4 py-2.5 text-white text-[13px] leading-relaxed bg-gradient-to-b from-brand to-brand-dark">{m.txt}</div>
                  : <div key={i} className="max-w-[85%] rounded-2xl rounded-tl-md px-4 py-2.5 bg-surface-subtle border border-line/70 text-[13px] text-ink leading-relaxed">{m.txt}</div>
              ))}
              {typing && <div className="w-14 rounded-2xl rounded-tl-md px-4 py-2.5 bg-surface-subtle border border-line/70 text-[13px] text-ink-soft tracking-widest">•••</div>}
            </div>
            <div className="flex items-center gap-2 pt-3 border-t border-line">
              <input value={chatDraft} onChange={e=>setChatDraft(e.target.value)} onKeyDown={e=>e.key==='Enter'&&chatSend()} placeholder="Type a message…"
                className="flex-1 bg-surface-input rounded-full px-4 py-2.5 text-[13px] text-ink placeholder:text-ink-soft outline-none focus:bg-white focus:border-brand-200 border border-transparent acc-ring transition"/>
              <button onClick={chatSend} disabled={!chatDraft.trim()} className="w-10 h-10 shrink-0 rounded-full text-white bg-gradient-to-b from-brand to-brand-dark shadow-btn disabled:opacity-40 flex items-center justify-center"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M22 2L11 13M22 2l-7 20-4-9-9-4z" strokeLinejoin="round"></path></svg></button>
            </div>
          </div>
        ) : sent ? (
          <div className="text-center py-6">
            <span className="mx-auto w-14 h-14 rounded-full bg-green-50 text-green-600 flex items-center justify-center"><svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M20 6L9 17l-5-5"></path></svg></span>
            <p className="text-[16px] font-extrabold text-ink mt-4">We've received your query</p>
            <p className="text-[13px] text-ink-muted mt-1.5 leading-relaxed">Our support team will reply within <b className="text-ink">48 hours max</b> — you'll get the reply here.</p>
            <button onClick={openAdminInbox} className="mt-4 text-[12px] font-bold acc-text underline underline-offset-2">See it in the Admin support inbox (demo) →</button>
            <div><button onClick={close} className="mt-4 rounded-full px-6 py-2.5 text-[13px] font-bold text-white bg-gradient-to-b from-brand to-brand-dark shadow-btn">Done</button></div>
          </div>
        ) : (
          <>
            <p className="text-[16px] font-extrabold text-ink">Help &amp; Support</p>
            <p className="text-[12.5px] text-ink-muted mt-1 leading-relaxed">Quick answers, or message our team — we reply within 48 hours.</p>
            <div className="mt-4 grid grid-cols-2 gap-2">
              {[['Getting started guide','knowledge'],['QR & insert setup','knowledge'],['Billing & invoices','settings'],['Claim page languages','knowledge']].map(([lb,go])=>(
                <button key={lb} onClick={()=>{ close(); window.__sellerNav && window.__sellerNav(go); }} className="text-left px-3.5 py-3 rounded-xl bg-surface-subtle border border-line text-[12.5px] font-bold text-ink hover:border-brand-200 transition-colors">{lb}</button>
              ))}
            </div>
            <div className="mt-4">
              <button onClick={()=>setChat(true)} className="w-full flex items-center gap-3 px-4 py-3 rounded-xl border border-brand-200 bg-white hover:bg-surface-subtle transition-colors text-left">
                <span className="relative w-9 h-9 shrink-0 rounded-full bg-surface-subtle border border-line flex items-center justify-center text-[13px] font-extrabold acc-text">R<span className="absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full bg-green-500 border-2 border-white"></span></span>
                <span className="flex-1 min-w-0"><span className="block text-[13px] font-extrabold text-ink">Chat with a live agent</span><span className="block text-[11.5px] text-green-600 font-bold">Online now · replies in ~1 min</span></span>
                <svg className="shrink-0 text-ink-soft" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M9 6l6 6-6 6" strokeLinecap="round"></path></svg>
              </button>
            </div>
            <p className="mt-5 text-[10.5px] font-bold uppercase tracking-wider text-ink-soft">Or leave a message</p>
            <div className="mt-3 space-y-4">
              <Field label="What do you need help with?">
                <Select value={cat} onChange={e=>setCat(e.target.value)}>
                  {['Payouts & rewards','Campaigns & QR codes','Claim page','Billing & plans','Account & compliance','Something else'].map(o=><option key={o}>{o}</option>)}
                </Select>
              </Field>
              <Field label="Message" required>
                <textarea rows="3" value={msg} onChange={e=>setMsg(e.target.value)} placeholder="Eg. 14 approved cashback claims show 'processing' since Monday"
                  className="w-full bg-surface-input rounded-xl px-4 py-3 text-[13px] text-ink placeholder:text-ink-soft outline-none focus:bg-white focus:border-brand-200 border border-transparent acc-ring transition resize-y"></textarea>
              </Field>
              <div className="flex items-center justify-end gap-2 pt-1">
                <button onClick={close} className="rounded-full px-5 py-2.5 text-[13px] font-bold text-ink-muted hover:text-ink transition-colors">Cancel</button>
                <button onClick={()=>msg.trim()&&setSent(true)} className="whitespace-nowrap rounded-full px-6 py-2.5 text-[13px] font-bold text-white bg-gradient-to-b from-brand to-brand-dark shadow-btn disabled:opacity-40" disabled={!msg.trim()}>Send to support</button>
              </div>
            </div>
          </>
        )}
      </div>
    </div>, document.body);
}

/* Suggest-a-feature — sellers pitch improvements; rewarded if implemented */
function SuggestFeature() {
  const [open, setOpen] = React.useState(false);
  const [sent, setSent] = React.useState(false);
  const [area, setArea] = React.useState('Dashboard');
  const [idea, setIdea] = React.useState('');
  const [why, setWhy] = React.useState('');
  const close = () => { setOpen(false); setTimeout(()=>{ setSent(false); setIdea(''); setWhy(''); }, 300); };
  return (
    <>
      <button onClick={()=>setOpen(true)}
        className="hidden sm:inline-flex items-center gap-2 h-10 px-4 rounded-full bg-white border border-line hover:border-brand-200 text-[12.5px] font-bold text-ink-muted hover:text-brand transition-colors whitespace-nowrap">
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 18h6M10 22h4M12 2a7 7 0 0 0-4 12.7c.6.5 1 1.4 1 2.3h6c0-.9.4-1.8 1-2.3A7 7 0 0 0 12 2z"/></svg>
        Suggest a feature
      </button>
      {open && ReactDOM.createPortal(
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-ink/40 p-4" onClick={close}>
          <div className="bg-white rounded-3xl shadow-pop p-7 w-full max-w-[440px]" onClick={e=>e.stopPropagation()}>
            {sent ? (
              <div className="text-center py-6">
                <span className="mx-auto w-14 h-14 rounded-full bg-green-50 text-green-600 flex items-center justify-center"><svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M20 6L9 17l-5-5"/></svg></span>
                <p className="text-[16px] font-extrabold text-ink mt-4">Idea received!</p>
                <p className="text-[13px] text-ink-muted mt-1.5 leading-relaxed">Our team reviews every suggestion. If we implement yours, you'll get <b className="text-ink">1 month of Pro free</b> — we'll notify you here and by email.</p>
                <button onClick={close} className="mt-5 rounded-full px-6 py-2.5 text-[13px] font-bold text-white bg-gradient-to-b from-brand to-brand-dark shadow-btn">Done</button>
              </div>
            ) : (
              <>
                <p className="text-[16px] font-extrabold text-ink">Suggest a feature</p>
                <p className="text-[12.5px] text-ink-muted mt-1 leading-relaxed">Help us improve ReviewBuddie. If we like your idea and ship it, you get <b className="text-ink">1 month of Pro free</b>.</p>
                <div className="mt-5 space-y-4">
                  <Field label="Which part of the product?">
                    <Select value={area} onChange={e=>setArea(e.target.value)}>
                      {['Dashboard','Products','Promotions','Campaigns','Claim Center','Customer claim page','QR codes','Billing / plans','Something else'].map(o=><option key={o}>{o}</option>)}
                    </Select>
                  </Field>
                  <Field label="Your idea" required>
                    <textarea rows="3" value={idea} onChange={e=>setIdea(e.target.value)} placeholder="Eg. Let me schedule campaigns to start on a future date"
                      className="w-full bg-surface-input rounded-xl px-4 py-3 text-[13px] text-ink placeholder:text-ink-soft outline-none focus:bg-white focus:border-brand-200 border border-transparent acc-ring transition resize-y"></textarea>
                  </Field>
                  <Field label="How would it help you?" hint="Optional — helps us prioritize">
                    <textarea rows="2" value={why} onChange={e=>setWhy(e.target.value)} placeholder="Eg. I launch inserts in batches and forget to activate them"
                      className="w-full bg-surface-input rounded-xl px-4 py-3 text-[13px] text-ink placeholder:text-ink-soft outline-none focus:bg-white focus:border-brand-200 border border-transparent acc-ring transition resize-y"></textarea>
                  </Field>
                </div>
                <div className="flex gap-2 mt-6">
                  <button disabled={!idea.trim()} onClick={()=>setSent(true)}
                    className={"flex-1 rounded-full py-2.5 text-[13px] font-bold text-white transition-all "+(idea.trim()?"bg-gradient-to-b from-brand to-brand-dark shadow-btn":"bg-brand-200 cursor-not-allowed")}>Submit idea</button>
                  <button onClick={close} className="flex-1 rounded-full py-2.5 text-[13px] font-bold text-ink border border-line hover:bg-surface-subtle">Cancel</button>
                </div>
              </>
            )}
          </div>
        </div>, document.body
      )}
    </>
  );
}

function Topbar() {
  return (
    <div className="h-[68px] bg-surface-canvas/80 backdrop-blur-md border-b border-line flex items-center justify-between px-7 sticky top-0 z-30">
      <div>
        <div className="text-[17px] font-bold text-ink leading-none tracking-tight">
          Welcome back, Demo User
        </div>
        <div className="text-[12.5px] text-ink-muted mt-1">Here's what's happening with your reviews today.</div>
      </div>
      <div className="flex items-center gap-2.5">
        <SuggestFeature/>
        {/* search */}
        <div className="relative hidden md:block">
          <svg className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-soft" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/>
          </svg>
          <input placeholder="Search…"
            className="w-52 bg-white border border-line rounded-full pl-9 pr-3 py-2.5 text-[13px] placeholder:text-ink-soft outline-none focus:w-64 focus:border-brand-200 transition-all acc-ring"/>
        </div>
        {/* bell */}
        <button className="relative w-10 h-10 rounded-full bg-white border border-line hover:border-brand-200 flex items-center justify-center text-ink-muted transition-colors">
          <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9"/>
            <path d="M13.7 21a2 2 0 0 1-3.4 0"/>
          </svg>
          <span className="absolute top-2 right-2.5 w-2 h-2 rounded-full bg-rose-500 ring-2 ring-surface-canvas"></span>
        </button>
        {/* avatar */}
        <button className="flex items-center gap-2.5 pl-1 pr-1 py-1 rounded-full hover:bg-white transition-colors">
          <span className="w-9 h-9 rounded-full text-white font-bold text-sm flex items-center justify-center"
                style={{ backgroundImage:'linear-gradient(135deg, var(--accent), var(--accent-dark))' }}>D</span>
        </button>
      </div>
    </div>
  );
}

/* InfoTip — ⓘ hover/click tooltip explaining a section */
function InfoTip({ text, dark=false }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const h = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h); return () => document.removeEventListener('mousedown', h);
  }, [open]);
  return (
    <span ref={ref} className="relative inline-flex group/tip align-middle">
      <button type="button" aria-label="What is this?" onClick={()=>setOpen(o=>!o)}
        className={"w-[17px] h-[17px] rounded-full border flex items-center justify-center text-[10px] font-bold leading-none transition-colors "+(dark?"border-white/40 text-white/60 hover:text-white hover:border-white":"border-ink-soft/50 text-ink-soft hover:text-brand hover:border-brand")}>i</button>
      <span className={"pointer-events-none absolute left-1/2 -translate-x-1/2 top-[calc(100%+8px)] z-40 w-60 rounded-xl bg-ink text-white text-[11.5px] font-medium leading-relaxed px-3.5 py-2.5 shadow-pop transition-opacity duration-150 "+(open?"opacity-100":"opacity-0 group-hover/tip:opacity-100")}>
        {text}
        <span className="absolute -top-1 left-1/2 -translate-x-1/2 w-2 h-2 bg-ink rotate-45"></span>
      </span>
    </span>
  );
}

/* Per-page descriptions shown by the ⓘ next to every page title */
const PAGE_INFO = {
  'Dashboard':'Your home base and analytics in one place — live performance, funnel drop-offs, and which products, campaigns and marketplaces earn the most.',
  'Products':'All products you collect reviews for. Add a product first — promotions and campaigns are built on top of it.',
  'Promotions':'The offers you give customers (gift, cashback, extended warranty…) in exchange for honest feedback.',
  'Create Promotion':'Build a new customer offer — pick a type, attach a brand and set what the customer receives.',
  'Campaigns':'A campaign connects a promotion to your products and generates the QR code / link customers scan.',
  'Add New Campaign':'Link a promotion to one or more products and launch it — you\u2019ll get a QR code and claim page.',
  'Add New Product':'Register a product with its marketplace listings so customers can be routed to the right review page.',
  'Generate Package Insert':'Design the printed card that goes inside your packaging with the QR code customers scan.',
  'Customers':'Everyone who claimed one of your promotions — their contact details, orders and review status.',
  'Claim Center':'Incoming customer claims to verify and deliver — approve, reject or fulfil rewards from here.',
  'Refer & Earn':'Invite other sellers to ReviewBuddie — you both earn rewards when they join and go active.',
  'Knowledge Center':'Guides, videos and articles from the ReviewBuddie team to help you get more from the platform.',
  'Settings':'Your account, brands, plan & billing, password and affiliate payout preferences.',
};

/* PageHeader — the strip beneath Topbar with breadcrumb/title + right-side action */
function PageHeader({ crumbs, title, action, info }) {
  const tip = info || PAGE_INFO[title];
  return (
    <div className="px-7 pt-7 pb-1">
      {crumbs && crumbs.length > 0 && (
        <div className="text-[12.5px] text-ink-muted mb-2 flex items-center gap-1.5 flex-wrap">
          {crumbs.map((c,i) => (
            <React.Fragment key={i}>
              {i > 0 && <span className="text-ink-soft">›</span>}
              <span className={i === crumbs.length-1 ? "text-ink font-semibold" : "text-ink-muted font-medium"}>{c}</span>
            </React.Fragment>
          ))}
        </div>
      )}
      <div className="flex items-center justify-between gap-4">
        <span className="flex items-center gap-2.5">
          <h1 className="text-[26px] font-extrabold tracking-[-0.02em] text-ink leading-none">{title}</h1>
          {tip && <InfoTip text={tip}/>}
        </span>
        {action}
      </div>
    </div>
  );
}

/* Primary CTA pill */
const BtnPrimary = ({ children, icon, onClick, type='button', disabled=false }) => (
  <button onClick={onClick} type={type} disabled={disabled}
    className={
      "inline-flex items-center gap-2 whitespace-nowrap shrink-0 rounded-full px-5 py-2.5 text-[13.5px] font-bold text-white transition-all duration-150 " +
      (disabled
        ? "bg-brand-200 cursor-not-allowed"
        : "bg-gradient-to-b from-brand to-brand-dark shadow-btn hover:shadow-lg hover:-translate-y-px active:translate-y-0")
    }>
    {icon}{children}
  </button>
);
const BtnGhost = ({ children, onClick }) => (
  <button onClick={onClick}
    className="inline-flex items-center gap-2 rounded-full px-5 py-2.5 text-[13.5px] font-bold text-ink border border-line bg-white hover:border-ink-soft hover:bg-surface-subtle transition-colors">
    {children}
  </button>
);

/* App shell — wraps everything */
function AppShell({ children, active, onNav }) {
  React.useEffect(() => { window.__sellerNav = onNav; }, [onNav]);
  return (
    <div className="flex min-h-screen bg-surface-canvas">
      <Sidebar active={active} onNav={onNav}/>
      <div className="flex-1 min-w-0 flex flex-col">
        <Topbar/>
        <main className="flex-1">{children}</main>
      </div>
      <HelpSupport/>
    </div>
  );
}

/* Generic small bits */
const Card = ({ children, className='' }) => (
  <div className={"bg-white rounded-2xl border border-line shadow-card " + className}>{children}</div>
);
const Field = ({ label, hint, children, required }) => (
  <label className="block">
    <span className="block text-[13px] font-bold text-ink mb-1.5">
      {label} {required && <span className="acc-text">*</span>}
    </span>
    {hint && <p className="text-[12px] text-ink-muted -mt-1 mb-2">{hint}</p>}
    {children}
  </label>
);
const Input = (props) => (
  <input
    {...props}
    className={"w-full bg-surface-input border border-transparent rounded-xl px-4 py-3 text-[14px] text-ink placeholder:text-ink-soft outline-none focus:bg-white focus:border-brand-200 acc-ring transition " + (props.className || '')}
  />
);
const Select = (props) => (
  <div className="relative">
    <select
      {...props}
      className={"w-full appearance-none bg-surface-input border border-transparent rounded-xl px-4 py-3 pr-10 text-[14px] text-ink outline-none focus:bg-white focus:border-brand-200 acc-ring transition " + (props.className || '')}>
      {props.children}
    </select>
    <svg className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none text-ink-muted" width="14" height="14" viewBox="0 0 24 24" fill="none">
      <path d="M6 9l6 6 6-6" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  </div>
);

/* Icon: edit + trash action buttons used in tables */
const RowActions = ({ onEdit, onDelete }) => (
  <div className="inline-flex items-center gap-2">
    <button onClick={onEdit}
      className="w-8 h-8 rounded-lg bg-brand-50 text-brand flex items-center justify-center hover:bg-brand hover:text-white transition-colors">
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2">
        <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
        <path d="M18.5 2.5a2.1 2.1 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
      </svg>
    </button>
    <button onClick={onDelete}
      className="w-8 h-8 rounded-lg bg-surface-input text-ink-muted hover:bg-rose-50 hover:text-rose-600 flex items-center justify-center transition-colors">
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2">
        <path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/>
      </svg>
    </button>
  </div>
);

const StatusToggle = ({ checked = true, onChange }) => (
  <input type="checkbox" className="ios-toggle" defaultChecked={checked} onChange={onChange}/>
);

/* tiny coloured chip */
const Chip = ({ tone = 'brand', children }) => {
  const map = {
    brand:'bg-brand-50 text-brand',
    green:'bg-green-50 text-green-700',
    amber:'bg-amber-50 text-amber-700',
    slate:'bg-slate-100 text-slate-600',
    rose: 'bg-rose-50 text-rose-700',
  };
  return <span className={"inline-flex items-center gap-1 text-[10.5px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-full "+map[tone]}>{children}</span>;
};

/* Tiny phone preview frame used in Promotion / Campaign create forms */
function PhonePreview({ children, label='Preview' }) {
  return (
    <div className="flex flex-col items-center">
      <span className="px-3 py-1 text-[11px] font-semibold rounded-full bg-brand-50 text-brand mb-4">{label}</span>
      <div className="relative bg-[#0E0D0B] rounded-[36px] p-2.5 shadow-2xl" style={{width:240,height:480}}>
        <div className="absolute left-1/2 -translate-x-1/2 top-3 w-20 h-5 bg-black rounded-full z-10"></div>
        <div className="w-full h-full bg-white rounded-[28px] overflow-hidden flex flex-col">
          {children}
        </div>
      </div>
    </div>
  );
}

/* Search row used by list pages */
const SearchInput = ({ placeholder='Search', value, onChange }) => (
  <div className="relative max-w-md w-full">
    <svg className="absolute left-3.5 top-1/2 -translate-y-1/2 text-ink-soft" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/>
    </svg>
    <input
      {...(onChange ? { value, onChange } : {})}
      placeholder={placeholder}
      className="w-full bg-white border border-line rounded-xl pl-10 pr-3 py-2.5 text-[13.5px] placeholder:text-ink-soft outline-none focus:border-brand-200 acc-ring transition"/>
  </div>
);

Object.assign(window, {
  Logo, Sidebar, Topbar, PageHeader, AppShell, SuggestFeature, InfoTip, HelpSupport,
  BtnPrimary, BtnGhost, Card, Field, Input, Select,
  RowActions, StatusToggle, Chip, PhonePreview, SearchInput, NAV,
});
