/* Knowledge Center — scalable content library: guides, blogs, videos, FAQs.
   Built for AI/SEO discoverability: every item has slug, category, tags, updated date. */
const KC_CATS = [
  { id:'start',  label:'Getting started' },
  { id:'promos', label:'Promotions' },
  { id:'claims', label:'Claim Center' },
  { id:'reviews',label:'Reviews & compliance' },
  { id:'billing',label:'Billing & plans' },
];
const KC_ITEMS = [
  { type:'guide', t:'The 3-step flow: Product → Promotion → Campaign', cat:'start',  mins:3, updated:'Jul 2026', tags:['setup','campaign'] },
  { type:'guide', t:'Adding your first product', cat:'start', mins:2, updated:'Jul 2026', tags:['setup'] },
  { type:'guide', t:'Choosing the right promotion type', cat:'promos', mins:4, updated:'Jun 2026', tags:['cashback','warranty','giftcard'] },
  { type:'guide', t:'Setting up cashback via UPI', cat:'promos', mins:3, updated:'Jun 2026', tags:['cashback','upi'] },
  { type:'guide', t:'How the claim verification flow works', cat:'claims', mins:4, updated:'Jul 2026', tags:['claims'] },
  { type:'guide', t:'Marking claims as delivered', cat:'claims', mins:2, updated:'May 2026', tags:['claims','payout'] },
  { type:'guide', t:'Upgrading, downgrading & invoices', cat:'billing', mins:3, updated:'Jun 2026', tags:['billing'] },
  { type:'blog',  t:'Why package inserts still outperform email for reviews', cat:'reviews', mins:6, updated:'Jul 2026', tags:['inserts','strategy'] },
  { type:'blog',  t:'Amazon review policy in 2026: what sellers can and can\u2019t do', cat:'reviews', mins:8, updated:'Jul 2026', tags:['compliance','amazon'] },
  { type:'blog',  t:'Cashback vs. gift cards: which promotion converts better?', cat:'promos', mins:5, updated:'Jun 2026', tags:['strategy'] },
  { type:'video', t:'Set up your first campaign in 5 minutes', cat:'start', dur:'4:52', updated:'Jul 2026', tags:['setup'] },
  { type:'video', t:'Designing a package insert that gets scanned', cat:'promos', dur:'6:10', updated:'Jun 2026', tags:['inserts'] },
  { type:'video', t:'Approving & paying out claims', cat:'claims', dur:'3:38', updated:'Jun 2026', tags:['claims'] },
];
const KC_FAQS = [
  { cat:'reviews', q:'Is rewarding reviews compliant with marketplace policies?', a:'Reviewbuddie is built around policy-safe flows: rewards are for feedback participation, never conditioned on a positive rating. Always review your marketplace\u2019s latest terms — we keep templates updated for Amazon, Flipkart and Meesho.' },
  { cat:'start', q:'How do customers reach my promotion?', a:'Each campaign generates a unique QR code and short link. Print the QR on your package insert — customers scan it, complete the review flow, and their claim lands in your Claim Center.' },
  { cat:'claims', q:'When do I pay out a cashback claim?', a:'Only after you approve it in the Claim Center. You collect the customer\u2019s UPI ID during the flow, pay them directly, and mark the claim as delivered.' },
  { cat:'promos', q:'Can I run multiple campaigns for the same product?', a:'Yes — each campaign gets its own QR code and analytics, so you can test different promotions against each other.' },
  { cat:'billing', q:'What happens when I hit my plan\u2019s review limit?', a:'New claims keep collecting but stay locked until you upgrade or the next billing cycle starts. You\u2019ll never lose a claim.' },
];
const KC_TYPES = [
  { id:'all',   label:'All' },
  { id:'guide', label:'How-to guides' },
  { id:'blog',  label:'Blogs' },
  { id:'video', label:'Videos' },
  { id:'faq',   label:'FAQs' },
];
const KC_TYPE_META = {
  guide: { label:'Guide', cls:'bg-sky-50 text-sky-700' },
  blog:  { label:'Blog',  cls:'bg-violet-50 text-violet-700' },
  video: { label:'Video', cls:'bg-rose-50 text-rose-600' },
};
function KCItemRow({ item }) {
  const toast = (m) => window.rbToast ? window.rbToast(m) : null;
  const meta = KC_TYPE_META[item.type];
  const catLabel = (KC_CATS.find(c=>c.id===item.cat)||{}).label;
  return (
    <button onClick={()=>toast(item.type==='video' ? 'Video player coming soon (demo)' : 'Article opening soon (demo)')} className="w-full flex items-center gap-4 px-5 py-3.5 text-left hover:bg-surface-subtle transition group">
      {item.type==='video'
        ? <span className="w-9 h-9 rounded-lg bg-gradient-to-br from-[#0E1A24] to-[#16283a] flex items-center justify-center shrink-0">
            <svg width="13" height="13" viewBox="0 0 24 24" className="text-white ml-0.5" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>
          </span>
        : <span className="w-9 h-9 rounded-lg acc-bg-soft acc-text flex items-center justify-center shrink-0">
            <svg width="14" height="14" 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>
          </span>}
      <span className="min-w-0 flex-1">
        <span className="block text-[13.5px] font-bold text-ink leading-snug truncate group-hover:text-brand transition-colors">{item.t}</span>
        <span className="block text-[11.5px] text-ink-soft mt-0.5">{catLabel} · {item.type==='video' ? item.dur : item.mins + ' min read'} · Updated {item.updated}</span>
      </span>
      <span className={"shrink-0 px-2 py-0.5 rounded-full text-[10.5px] font-bold " + meta.cls}>{meta.label}</span>
      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="shrink-0 text-ink-soft"><path d="m9 18 6-6-6-6"/></svg>
    </button>
  );
}
function KCFaqItem({ f, open, onToggle }) {
  const catLabel = (KC_CATS.find(c=>c.id===f.cat)||{}).label;
  return (
    <div className="border-b border-gray-100 last:border-0">
      <button onClick={onToggle} className="w-full flex items-center justify-between gap-4 py-4 text-left">
        <span>
          <span className="block text-[13.5px] font-bold text-ink">{f.q}</span>
          <span className="block text-[11px] text-ink-soft mt-0.5">{catLabel}</span>
        </span>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" className={"shrink-0 text-ink-soft transition-transform " + (open ? 'rotate-45' : '')}><path d="M12 5v14M5 12h14"/></svg>
      </button>
      {open && <p className="text-[13px] text-ink-muted leading-relaxed pb-4 pr-8 -mt-1">{f.a}</p>}
    </div>
  );
}
function KnowledgeCenter() {
  const [query, setQuery] = React.useState('');
  const [type, setType] = React.useState('all');
  const [cat, setCat] = React.useState('all');
  const [openFaq, setOpenFaq] = React.useState(0);
  const toast = (m) => window.rbToast ? window.rbToast(m) : null;
  const q = query.toLowerCase();
  const match = (txt) => !q || txt.toLowerCase().includes(q);
  const items = KC_ITEMS.filter(i =>
    (type==='all' || i.type===type) && type!=='faq' &&
    (cat==='all' || i.cat===cat) &&
    match(i.t + ' ' + (i.tags||[]).join(' ')));
  const faqs = (type==='all' || type==='faq') ? KC_FAQS.filter(f => (cat==='all' || f.cat===cat) && match(f.q + ' ' + f.a)) : [];
  const showItems = type!=='faq';
  return (
    <>
      <PageHeader title="Knowledge Center" action={
        <BtnPrimary onClick={()=>toast('Content upload flow coming soon (demo)')}>+ Add content</BtnPrimary>
      }/>
      <div className="px-7 py-6 space-y-6 max-w-[1020px]">
        {/* Search hero */}
        <div className="rounded-2xl text-white px-7 py-8 text-center" style={{backgroundColor:'#0E1A24', backgroundImage:'radial-gradient(80% 140% at 50% 0%, rgba(14,154,214,0.25), transparent 65%)'}}>
          <h2 className="text-[22px] font-extrabold">How can we help?</h2>
          <div className="mt-4 max-w-[460px] mx-auto relative">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="absolute left-4 top-1/2 -translate-y-1/2 text-white/50"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>
            <input value={query} onChange={e=>setQuery(e.target.value)} placeholder="Search guides, blogs, videos and FAQs…"
              className="w-full h-11 rounded-xl bg-white/10 border border-white/20 pl-11 pr-4 text-[13.5px] text-white placeholder:text-white/50 outline-none focus:border-white/40"/>
          </div>
        </div>
        {/* Type tabs + category chips */}
        <div className="space-y-3">
          <div className="inline-flex p-1 rounded-xl bg-surface-subtle border border-line gap-1 flex-wrap">
            {KC_TYPES.map(t=>(
              <button key={t.id} onClick={()=>setType(t.id)} className={"px-3.5 py-2 rounded-lg text-[12.5px] font-bold transition " + (type===t.id ? 'bg-white text-ink shadow-soft' : 'text-ink-muted hover:text-ink')}>{t.label}</button>
            ))}
          </div>
          <div className="flex items-center gap-2 flex-wrap">
            {[{id:'all',label:'All topics'},...KC_CATS].map(c=>(
              <button key={c.id} onClick={()=>setCat(c.id)} className={"px-3 py-1.5 rounded-full text-[11.5px] font-bold border transition " + (cat===c.id ? 'acc-bg text-white border-transparent' : 'border-line text-ink-muted hover:text-ink')}>{c.label}</button>
            ))}
          </div>
        </div>
        {/* Content grid */}
        {showItems && items.length>0 && (
          <Card className="overflow-hidden divide-y divide-gray-100">
            {items.map((it,i)=><KCItemRow key={i} item={it}/>)}
          </Card>
        )}
        {showItems && items.length===0 && faqs.length===0 && (
          <p className="text-[13px] text-ink-muted py-8 text-center">Nothing matches your search.</p>
        )}
        {/* FAQs */}
        {faqs.length>0 && (
          <div>
            <h3 className="text-[15px] font-extrabold text-ink mb-1">FAQs</h3>
            <Card className="px-6 py-1">
              {faqs.map((f,i)=><KCFaqItem key={i} f={f} open={openFaq===i} onToggle={()=>setOpenFaq(openFaq===i ? -1 : i)}/>)}
            </Card>
          </div>
        )}
        {/* Contact */}
        <Card className="p-5 flex items-center justify-between gap-4 flex-wrap">
          <div>
            <p className="text-[13px] font-bold text-ink">Still stuck?</p>
            <p className="text-[12px] text-ink-muted mt-0.5">Our team replies within a few hours on business days.</p>
          </div>
          <div className="flex gap-2.5">
            <button onClick={()=>toast('Opening WhatsApp support (demo)')} className="h-9 px-4 rounded-xl text-[12.5px] font-bold text-brand border border-brand/30 hover:bg-brand/5 transition">WhatsApp us</button>
            <button onClick={()=>toast('Support ticket form (demo)')} className="h-9 px-4 rounded-xl text-[12.5px] font-bold text-white bg-gradient-to-b from-brand to-brand-dark shadow-btn hover:shadow-lg transition">Contact support</button>
          </div>
        </Card>
      </div>
    </>
  );
}
Object.assign(window, { KnowledgeCenter });
