/* ─── Seller Panel — form screens (create/edit flows) ────────────────────────
   Add Product, Create Promotion, Add Campaign, Package Inserts. */

/* ── ADD PRODUCT ───────────────────────────────────────────────────────────── */
const COUNTRIES = ['India','USA','Canada','UK','Australia'];
const MARKETPLACES = [
  /* products */
  { k:'amazon',      label:'Amazon',           hint:'Amazon product URL',                 popular:true,
    how:['Open your product page on Amazon (Seller Central \u2192 Manage Inventory \u2192 View).','Copy the page URL and paste it here. We detect the ASIN automatically.'] },
  { k:'ebay',        label:'eBay',             hint:'eBay listing URL',                   popular:true, only:['USA','Canada','UK','Australia'],
    how:['Seller Hub \u2192 Listings \u2192 open the item.','Copy the URL and paste it here.'] },
  { k:'etsy',        label:'Etsy',             hint:'Etsy listing URL',                   popular:true, only:['USA','Canada'],
    how:['Shop Manager \u2192 Listings \u2192 open the listing \u2192 Preview.','Copy the URL and paste it here.'] },
  { k:'flipkart',    label:'Flipkart',         hint:'Flipkart product URL',               popular:true, only:['India'],
    how:['Seller Hub \u2192 My Listings \u2192 open your product.','Copy the URL and paste it here.'] },
  { k:'myntra',      label:'Myntra',           hint:'Myntra product URL',                 only:['India'],
    how:['Seller Portal \u2192 Products \u2192 open your product.','Copy the URL and paste it here.'] },
  { k:'nykaa',       label:'Nykaa',            hint:'Nykaa product URL',                  only:['India'],
    how:['Seller Portal \u2192 open your product listing.','Copy the URL and paste it here.'] },
  { k:'meesho',      label:'Meesho',           hint:'Meesho product link (Share \u2192 Copy link)', only:['India'],
    how:['Supplier Panel \u2192 My Products.','Tap Share on the product and copy the link.','Paste it here.'] },
  { k:'walmart',     label:'Walmart',          hint:'Walmart product URL',                only:['USA'],
    how:['Seller Center \u2192 Manage Items \u2192 open the item.','Copy the URL and paste it here.'] },
  { k:'target',      label:'Target',           hint:'Target product URL',                 only:['USA'],
    how:['Open your product on Target.com.','Copy the URL and paste it here.'] },
  { k:'homedepot',   label:'Home Depot',       hint:'Home Depot product URL',             only:['USA'],
    how:['Open your product on HomeDepot.com.','Copy the URL and paste it here.'] },
  { k:'bestbuy',     label:'Best Buy',         hint:'Best Buy product URL',               only:['USA'],
    how:['Open your product on BestBuy.com.','Copy the URL and paste it here.'] },
  { k:'wayfair',     label:'Wayfair',          hint:'Wayfair product URL',                only:['USA'],
    how:['Open your product on Wayfair.','Copy the URL and paste it here.'] },
  { k:'chewy',       label:'Chewy',            hint:'Chewy product URL',                  only:['USA'],
    how:['Open your product on Chewy.com.','Copy the URL and paste it here.'] },
  { k:'walmart_ca',  label:'Walmart Canada',   hint:'Walmart.ca product URL',             only:['Canada'],
    how:['Walmart Canada Seller Portal \u2192 Items \u2192 open the item.','Copy the URL and paste it here.'] },
  { k:'bestbuy_ca',  label:'Best Buy Canada',  hint:'BestBuy.ca product URL',             only:['Canada'],
    how:['Open your product on BestBuy.ca.','Copy the URL and paste it here.'] },
  { k:'homedepot_ca',label:'Home Depot Canada',hint:'HomeDepot.ca product URL',           only:['Canada'],
    how:['Open your product on HomeDepot.ca.','Copy the URL and paste it here.'] },
  { k:'cdntire',     label:'Canadian Tire',    hint:'Canadian Tire product URL',          only:['Canada'],
    how:['Open your product on CanadianTire.ca.','Copy the URL and paste it here.'] },
  { k:'asos',        label:'ASOS',             hint:'ASOS product URL',                   only:['UK'],
    how:['Open your product on ASOS.','Copy the URL and paste it here.'] },
  { k:'currys',      label:'Currys',           hint:'Currys product URL',                 only:['UK'],
    how:['Open your product on Currys.co.uk.','Copy the URL and paste it here.'] },
  { k:'zalando',     label:'Zalando',          hint:'Zalando product URL',                only:['UK'],
    how:['Partner Program \u2192 Products \u2192 open the product.','Copy the URL and paste it here.'] },
  { k:'catch',       label:'Catch',            hint:'Catch product URL',                  only:['Australia'],
    how:['Open your product in the Catch seller portal.','Copy the URL and paste it here.'] },
  { k:'kogan',       label:'Kogan',            hint:'Kogan product URL',                  only:['Australia'],
    how:['Open your product in the Kogan seller portal.','Copy the URL and paste it here.'] },
  { k:'mydeal',      label:'MyDeal',           hint:'MyDeal product URL',                 only:['Australia'],
    how:['Open your product in the MyDeal seller portal.','Copy the URL and paste it here.'] },
  /* services */
  { k:'google',      label:'Google Business Profile', hint:'Google review share link or Maps URL', popular:true, service:true,
    how:['Go to your Business Profile (business.google.com).','Select \u2018Read Reviews\u2019 \u2192 \u2018Get more reviews\u2019.','Copy the share link and paste it here. (Or just paste your Google Maps business link.)'] },
  { k:'trustpilot',  label:'Trustpilot',       hint:'Your website URL or domain',         popular:true, service:true,
    how:['Enter your website address (e.g. yourbrand.com).','That\u2019s it \u2014 no account linking needed.'] },
  { k:'zomato',      label:'Zomato',           hint:'Zomato restaurant URL',              only:['India'], service:true,
    how:['Zomato for Business \u2192 View on Zomato.','Copy the restaurant URL and paste it here.'] },
  { k:'facebook',    label:'Facebook Page',    hint:'Facebook Page URL',                  service:true,
    how:['Open your Facebook Page.','Copy the URL from the address bar and paste it here.','\u26a0\ufe0f Reviews/Recommendations must be turned ON in Page Settings \u2014 we check this for you.'] },
  { k:'checkatrade', label:'Checkatrade',      hint:'Checkatrade profile URL',            only:['UK'], service:true,
    how:['Open your Checkatrade profile.','Copy the URL and paste it here.'] },
  { k:'productreview',label:'ProductReview.com.au', hint:'ProductReview listing URL',     only:['Australia'], service:true,
    how:['Search your brand on ProductReview.com.au.','Open your listing, copy the URL and paste it here.'] },
  { k:'tripadvisor', label:'TripAdvisor',      hint:'TripAdvisor listing URL',            service:true,
    how:['Open your listing on TripAdvisor.','Copy the URL and paste it here. We extract everything automatically \u2014 no IDs to look up.'] },
  /* custom — available everywhere, both types */
  { k:'custom',      label:'Add your own marketplace', hint:'Preferred review link (URL)', custom:true,
    how:['Open your listing or profile on the marketplace.','Copy the link to the page where customers leave reviews.','Paste it here with the marketplace name.'] },
];

/* light format check per marketplace input */
const mktInputOk = (k, v) => {
  const s = (v || '').trim();
  if (!s) return false;
  if (k === 'trustpilot') return /^(https?:\/\/)?(www\.)?[a-z0-9.-]+\.[a-z]{2,}/i.test(s);
  return /^(https?:\/\/)?\S+\.\S{2,}/.test(s);
};

function AddProduct({ onNav }) {
  const [step,          setStep]         = React.useState(1);
  const [ltype,         setLtype]        = React.useState('product');   // product | service
  const [country,       setCountry]      = React.useState('India');
  const [mkts,          setMkts]         = React.useState({});
  const [productName,   setProductName]  = React.useState('');
  const [bulletInputs,  setBulletInputs] = React.useState(['','','','','']);
  const [tags,          setTags]         = React.useState([]);
  const [generating,    setGenerating]   = React.useState(false);
  const [aiError,       setAiError]      = React.useState('');
  const [selectedTags,  setSelectedTags] = React.useState([]);
  const [widgetStars,   setWidgetStars]  = React.useState(0);
  const [hoverStars,    setHoverStars]   = React.useState(0);
  const [image,         setImage]        = React.useState(null);
  const [customName,    setCustomName]   = React.useState('');
  const [infoKey,       setInfoKey]      = React.useState(null);
  const [videos,        setVideos]       = React.useState([{url:'',tagline:'How to use',file:null}]);
  const [eduFiles,      setEduFiles]     = React.useState([{kind:'User manual',url:'',file:null},{kind:'Care instructions',url:'',file:null},{kind:'Product link',url:'',file:null}]);

  const toggleMkt = k => setMkts(p => {
    if (k in p) { const n={...p}; delete n[k]; return n; }
    return {...p, [k]:''};
  });
  const setMktUrl = (k, url) => setMkts(p => ({...p, [k]: url}));
  const selectedMktCount = Object.keys(mkts).length;
  const setBullet = (i, val) => { const n=[...bulletInputs]; n[i]=val; setBulletInputs(n); };
  const toggleTag = tag => setSelectedTags(p => p.includes(tag)?p.filter(t=>t!==tag):[...p,tag]);
  const canNext = step===1 ? selectedMktCount>0 : step===2 ? productName.trim().length>0 : true;
  const loadImageFile = f => { if(!f || !f.type.startsWith('image/')) return; const r=new FileReader(); r.onload=()=>setImage(r.result); r.readAsDataURL(f); };

  const AI_INSTRUCTIONS = `You convert product or service feature bullets into short, tappable keyword tags for a customer review widget. Each tag is the aspect a shopper would tap to say what they liked or disliked about that feature.
Rules: Produce 1-2 tags per bullet. Return 3-5 tags total. 1-3 words each, Title Case, neutral aspect names only (no sentiment, no banned marketing words). Return ONLY a flat JSON array of strings.`;

  const goToPreview = async () => {
    const lines = bulletInputs.filter(Boolean);
    setGenerating(true); setAiError(''); setSelectedTags([]);
    try {
      if (lines.length) {
        const text = await window.claude.complete({
          messages:[{role:'user', content:`${AI_INSTRUCTIONS}\n\nProduct features:\n${lines.map((l,i)=>`${i+1}. ${l}`).join('\n')}`}]
        });
        const parsed = JSON.parse(text.trim());
        setTags(Array.isArray(parsed) ? parsed.slice(0,5) : []);
      }
    } catch(e) { setAiError('Could not generate tags — try again.'); }
    finally { setGenerating(false); setStep(3); }
  };

  /* ── Stepper ── */
  const STEPS = [
    { n:1, label:'Target & Marketplace' },
    { n:2, label:'Product Details' },
    { n:3, label:'Preview' },
  ];
  const StepBar = () => (
    <div className="flex items-center gap-0">
      {STEPS.map((s,i) => (
        <React.Fragment key={s.n}>
          <div className="flex flex-col items-center gap-1.5">
            <div className={"w-8 h-8 rounded-full flex items-center justify-center text-[13px] font-bold transition-all " +
              (step===s.n ? 'acc-bg text-white shadow-btn' : step>s.n ? 'bg-accent-200 acc-text' : 'bg-gray-100 text-ink-muted')}>
              {step > s.n
                ? <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M2.5 7l3 3 6-6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
                : s.n}
            </div>
            <span className={"text-[11.5px] font-semibold whitespace-nowrap " + (step===s.n ? 'acc-text' : 'text-ink-muted')}>{s.label}</span>
          </div>
          {i < STEPS.length-1 && (
            <div className={"flex-1 h-0.5 mx-3 mb-5 rounded-full transition-all " + (step>s.n ? 'acc-bg' : 'bg-gray-200')}
              style={{minWidth:60}}/>
          )}
        </React.Fragment>
      ))}
    </div>
  );

  /* ══════════════════════════════════════════════════════
     STEP 1 — Target & Marketplace
  ══════════════════════════════════════════════════════ */
  const Step1 = () => (
    <div className="space-y-6">
      <div>
        <h4 className="text-[13px] font-bold text-ink mb-1">What are you adding?</h4>
        <p className="text-[12px] text-ink-muted mb-3">This sets the labels, review platforms and promotion types that apply.</p>
        <div className="flex gap-2 max-w-md">
          {[['product','Physical product','Sold on marketplaces \u00b7 shipped'],['service','Service','Booked \u00b7 delivered in person or online']].map(([id,lb,hint])=>(
            <button key={id} onClick={()=>setLtype(id)}
              className={"flex-1 text-left rounded-xl border-2 p-3 transition-all "+(ltype===id?'border-[var(--accent)] bg-[var(--accent-50)]':'border-gray-200 bg-white hover:border-gray-300')}>
              <span className={"block text-[13px] font-bold "+(ltype===id?'acc-text':'text-ink')}>{lb}</span>
              <span className="block text-[11px] text-ink-muted mt-0.5">{hint}</span>
            </button>
          ))}
        </div>
      </div>
      <div className="border-t border-line pt-6">
        <h4 className="text-[13px] font-bold text-ink mb-1">Target Country</h4>
        <p className="text-[12px] text-ink-muted mb-3">Select the primary market for this {ltype}.</p>
        <div className="grid grid-cols-3 sm:grid-cols-5 gap-2">
          {COUNTRIES.map(c => (
            <button key={c} onClick={()=>setCountry(c)}
              className={"py-2.5 rounded-xl text-[12.5px] font-semibold border transition-all " +
                (country===c ? 'acc-bg text-white border-transparent shadow-btn' : 'bg-white border-gray-200 text-ink-muted hover:border-gray-300 hover:text-ink')}>
              {c}
            </button>
          ))}
        </div>
      </div>

      <div className="border-t border-line pt-6">
        <div className="flex items-center justify-between mb-1">
          <h4 className="text-[13px] font-bold text-ink">Marketplace Setup</h4>
          {selectedMktCount > 0 && (
            <span className="px-2.5 py-0.5 rounded-full text-[11px] font-bold acc-bg text-white">{selectedMktCount} active</span>
          )}
        </div>
        <p className="text-[12px] text-ink-muted mb-4">Click a platform to activate it, then paste the product URL.</p>
        {(() => {
          const visible = MARKETPLACES.filter(m => (!m.only || m.only.includes(country)) && (m.custom || (ltype==='service' ? m.service : !m.service)));
          const card = m => {
            const sel = m.k in mkts;
            const info = infoKey === m.k;
            return (
              <div key={m.k} onClick={()=>toggleMkt(m.k)}
                className={"relative rounded-xl border-2 p-3 cursor-pointer transition-all select-none self-start " +
                  (sel ? 'border-[var(--accent)] bg-[var(--accent-50)]' : 'border-gray-200 bg-white hover:border-gray-300')}>
                <div className="flex items-center gap-2">
                  <span className={"min-w-0 flex-1 truncate text-[13px] font-bold " + (sel?'acc-text':'text-ink-muted')} title={m.label}>{m.label}</span>
                  {m.how && (
                    <button aria-label={'How to get your '+m.hint} onClick={e=>{e.stopPropagation(); setInfoKey(info?null:m.k);}}
                      className={"w-5 h-5 rounded-full flex items-center justify-center shrink-0 text-[10px] font-bold border transition-all "+(info?'acc-bg text-white border-transparent':'border-gray-200 text-ink-soft hover:border-[var(--accent)] hover:acc-text bg-white')}>i</button>
                  )}
                  <span className={"w-5 h-5 rounded-full border-2 flex items-center justify-center shrink-0 transition-all " +
                    (sel ? 'acc-bg border-transparent' : 'border-gray-200 bg-white')}>
                    {sel && <svg width="9" height="9" viewBox="0 0 12 12" fill="none"><path d="M2 6l3 3 5-5" stroke="white" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/></svg>}
                  </span>
                </div>
                {info && (
                  <div onClick={e=>e.stopPropagation()}
                    className="absolute left-2 right-2 top-[calc(100%-6px)] z-20 bg-white border border-line rounded-xl shadow-card p-3">
                    <div className="flex items-center justify-between mb-1.5">
                      <p className="text-[10.5px] font-bold uppercase tracking-wide acc-text">How to get it</p>
                      <button aria-label="Close" onClick={()=>setInfoKey(null)} className="text-ink-soft hover:text-ink text-[12px] leading-none font-bold">{'\u2715'}</button>
                    </div>
                    <ol className="space-y-1.5">
                      {m.how.map((s,i)=>(
                        <li key={i} className="flex items-start gap-2 text-[11.5px] leading-snug text-ink-muted">
                          <span className="w-4 h-4 rounded-full acc-bg-soft acc-text flex items-center justify-center text-[9px] font-bold shrink-0 mt-px">{i+1}</span>
                          {s}
                        </li>
                      ))}
                    </ol>
                  </div>
                )}
                {sel && m.custom && (
                  <div className="mt-2" onClick={e=>e.stopPropagation()}>
                    <input value={customName} onChange={e=>setCustomName(e.target.value)}
                      placeholder="Marketplace name"
                      className="w-full bg-white rounded-lg px-2.5 py-1.5 text-[11.5px] text-ink border border-[var(--accent-50)] outline-none focus:border-[var(--accent)] transition-colors"/>
                  </div>
                )}
                {sel && (
                  <div className="relative mt-2" onClick={e=>e.stopPropagation()}>
                    <input
                      value={mkts[m.k]} onChange={e=>setMktUrl(m.k,e.target.value)}
                      placeholder={m.hint}
                      className="w-full bg-white rounded-lg pl-2.5 pr-7 py-1.5 text-[11.5px] text-ink border border-[var(--accent-50)] outline-none focus:border-[var(--accent)] transition-colors"/>
                    {mkts[m.k] && (mktInputOk(m.k, mkts[m.k])
                      ? <svg className="absolute right-2 top-1/2 -translate-y-1/2 text-green-600" width="12" height="12" viewBox="0 0 14 14" fill="none"><path d="M2.5 7l3 3 6-6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/></svg>
                      : <span title={'Doesn\'t look like a valid '+m.hint} className="absolute right-2 top-1/2 -translate-y-1/2 w-2 h-2 rounded-full bg-amber-400"></span>)}
                  </div>
                )}
              </div>
            );
          };
          return [['Popular', visible.filter(m=>m.popular)], ['More marketplaces', visible.filter(m=>!m.popular)]].map(([g,list]) => list.length ? (
            <div key={g} className="mb-4 last:mb-0">
              <p className="text-[10.5px] font-bold uppercase tracking-[0.12em] text-ink-soft mb-2">{g}</p>
              <div className="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-2.5 items-start">{list.map(card)}</div>
            </div>
          ) : null);
        })()}
      </div>
    </div>
  );

  /* ══════════════════════════════════════════════════════
     STEP 2 — Product Details
  ══════════════════════════════════════════════════════ */
  const Step2 = () => (
    <div className="space-y-6 max-w-xl">
      <div>
        <h4 className="text-[13px] font-bold text-ink mb-1">{ltype==='service'?'Service Name':'Product Name'}</h4>
        <p className="text-[12px] text-ink-muted mb-3">The name shown to customers in the review flow.</p>
        <Input placeholder={ltype==='service'?'e.g. Deep Home Cleaning \u2014 3 BHK':'e.g. Brontix WiFi Router Pro'} value={productName}
          onChange={e=>setProductName(e.target.value)}/>
      </div>

      <div className="border-t border-line pt-6">
        <h4 className="text-[13px] font-bold text-ink mb-1">{ltype==='service'?'Service Image':'Product Image'}</h4>
        <p className="text-[12px] text-ink-muted mb-3">Shown to customers in the review flow.</p>
        {image ? (
          <div className="flex items-center gap-4">
            <img src={image} alt="Product" className="w-20 h-20 rounded-xl object-cover border border-line shadow-soft"/>
            <div className="space-y-1">
              <label className="block text-[12.5px] font-bold acc-text cursor-pointer hover:opacity-80">
                Replace image
                <input type="file" accept="image/*" className="hidden" onChange={e=>loadImageFile(e.target.files[0])}/>
              </label>
              <button onClick={()=>setImage(null)} className="text-[12.5px] font-bold text-rose-600 hover:text-rose-700">Remove</button>
            </div>
          </div>
        ) : (
          <label onDragOver={e=>e.preventDefault()} onDrop={e=>{e.preventDefault(); loadImageFile(e.dataTransfer.files[0]);}}
            className="block border-2 border-dashed border-gray-200 hover:border-[var(--accent)] rounded-2xl py-8 text-center cursor-pointer transition-colors">
            <input type="file" accept="image/*" className="hidden" onChange={e=>loadImageFile(e.target.files[0])}/>
            <svg className="mx-auto text-ink-soft" width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12" strokeLinecap="round" strokeLinejoin="round"/></svg>
            <p className="text-[12.5px] font-semibold text-ink mt-2">Drag your image here or <span className="acc-text">browse</span></p>
            <p className="text-[11px] text-ink-soft mt-1">PNG or JPG up to 10 MB</p>
          </label>
        )}
      </div>

      <div className="border-t border-line pt-6">
        <h4 className="text-[13px] font-bold text-ink mb-1">{ltype==='service'?'Service Highlights':'Product Features'}</h4>
        <p className="text-[12px] text-ink-muted mb-4">
          Enter up to 5 key {ltype==='service'?'highlights':'features'}. AI will generate tappable review tags from these on the next step.
        </p>
        <div className="space-y-3">
          {bulletInputs.map((val, i) => (
            <div key={i} className="flex items-center gap-3">
              <span className={"w-7 h-7 rounded-full flex items-center justify-center text-[12px] font-bold shrink-0 transition-all " +
                (val ? 'acc-bg text-white' : 'bg-gray-100 text-ink-muted')}>
                {i+1}
              </span>
              <Input placeholder={`${ltype==='service'?'Highlight':'Feature'} ${i+1} — e.g. ${(ltype==='service'?['On-time arrival','Trained professionals','Eco-friendly supplies','30-day re-service guarantee','Transparent pricing']:['Long-lasting battery','108 MP camera','Slim aluminium build','120 Hz display','Fast charging'])[i]}`}
                value={val} onChange={e=>setBullet(i,e.target.value)}/>
            </div>
          ))}
        </div>
        {aiError && (
          <div className="mt-3 text-[12.5px] text-rose-600 bg-rose-50 rounded-lg px-3 py-2.5 border border-rose-100">{aiError}</div>
        )}
        <p className="text-[11px] text-ink-muted mt-3 flex items-center gap-1.5">
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="acc-text shrink-0">
            <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
          </svg>
          Click Next to auto-generate AI review tags from these features.
        </p>
      </div>

      <div className="border-t border-line pt-6">
        <h4 className="text-[13px] font-bold text-ink mb-1">Product Videos <span className="text-[11px] font-normal text-ink-muted ml-1">optional</span></h4>
        <p className="text-[12px] text-ink-muted mb-1">Shown to customers in the claim funnel — setup guides, how-to demos. Paste a URL or upload a file.</p>
        <p className="text-[12px] font-semibold acc-text mb-2">Increases customer experience and reduces returns by 3X.</p>
        <p className="text-[12px] text-ink mb-4 bg-[var(--accent-50)] border border-[var(--accent-50)] rounded-lg px-3 py-2"><b className="acc-text">Super tip:</b> Record a personal thank-you to your customers for choosing your brand — a 30-second hello turns a delivery into a relationship. 10X the experience.</p>
        <div className="space-y-3">
          {videos.map((v,i)=>(
            <div key={i} className="flex items-center gap-3">
              <div className="w-[150px] shrink-0 relative">
                <input list="rb-video-taglines" value={v.tagline} onChange={e=>{const n=[...videos];n[i]={...n[i],tagline:e.target.value};setVideos(n);}}
                  placeholder="e.g. How to use"
                  className="w-full h-10 rounded-xl border border-line bg-white pl-3 pr-7 text-[12.5px] font-semibold text-ink outline-none focus:border-[var(--accent)] placeholder:text-ink-soft"/>
                <button tabIndex={-1} onClick={e=>{const inp=e.currentTarget.previousSibling;const n=[...videos];n[i]={...n[i],tagline:''};setVideos(n);setTimeout(()=>inp.focus(),0);}}
                  className="absolute right-2 top-1/2 -translate-y-1/2 text-ink-soft hover:text-ink" aria-label="Show options">
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M6 9l6 6 6-6" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </button>
              </div>
              <input value={v.url} onChange={e=>{const n=[...videos];n[i]={...n[i],url:e.target.value,file:null};setVideos(n);}}
                placeholder="Paste YouTube / video URL"
                className="flex-1 h-10 rounded-xl border border-line bg-white px-3 text-[13px] text-ink outline-none focus:border-[var(--accent)] placeholder:text-ink-soft"/>
              <label className="h-10 px-3 rounded-xl border border-line bg-white flex items-center gap-1.5 text-[12px] font-bold acc-text cursor-pointer hover:border-[var(--accent)] transition-colors shrink-0">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12" strokeLinecap="round" strokeLinejoin="round"/></svg>
                {v.file ? v.file.slice(0,14) : 'Upload'}
                <input type="file" accept="video/*" className="hidden" onChange={e=>{const f=e.target.files[0];if(!f)return;const n=[...videos];n[i]={...n[i],file:f.name,url:''};setVideos(n);}}/>
              </label>
              {videos.length>1 && (
                <button onClick={()=>setVideos(videos.filter((_,j)=>j!==i))} className="text-ink-soft hover:text-rose-600 shrink-0" aria-label="Remove video">
                  <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6L6 18M6 6l12 12" strokeLinecap="round"/></svg>
                </button>
              )}
            </div>
          ))}
        </div>
        {videos.length<5 && (
          <button onClick={()=>setVideos([...videos,{url:'',tagline:'Setup instructions',file:null}])}
            className="mt-3 text-[12.5px] font-bold acc-text hover:opacity-80">+ Add another video</button>
        )}
      </div>

      <div className="border-t border-line pt-6">
        <h4 className="text-[13px] font-bold text-ink mb-1">Guides &amp; Links <span className="text-[11px] font-normal text-ink-muted ml-1">optional</span></h4>
        <p className="text-[12px] text-ink-muted mb-1">Up to 3 resources shown below the video in the funnel — upload a PDF or paste a link.</p>
        <p className="text-[12px] font-semibold acc-text mb-4">Tip: add your brand store link for cross-selling.</p>
        <div className="space-y-3">
          {eduFiles.map((f,i)=>(
            <div key={i} className="flex items-center gap-3">
              <div className="w-[150px] shrink-0 relative">
                <input list="rb-edu-kinds" value={f.kind} onChange={e=>{const n=[...eduFiles];n[i]={...n[i],kind:e.target.value};setEduFiles(n);}}
                  placeholder="e.g. User manual"
                  className="w-full h-10 rounded-xl border border-line bg-white pl-3 pr-7 text-[12.5px] font-semibold text-ink outline-none focus:border-[var(--accent)] placeholder:text-ink-soft"/>
                <button tabIndex={-1} onClick={e=>{const inp=e.currentTarget.previousSibling;const n=[...eduFiles];n[i]={...n[i],kind:''};setEduFiles(n);setTimeout(()=>inp.focus(),0);}}
                  className="absolute right-2 top-1/2 -translate-y-1/2 text-ink-soft hover:text-ink" aria-label="Show options">
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M6 9l6 6 6-6" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </button>
              </div>
              <input value={f.url} onChange={e=>{const n=[...eduFiles];n[i]={...n[i],url:e.target.value,file:null};setEduFiles(n);}}
                placeholder={f.kind==='Product link' ? 'Paste product / storefront URL' : 'Paste link or upload PDF'}
                className="flex-1 h-10 rounded-xl border border-line bg-white px-3 text-[13px] text-ink outline-none focus:border-[var(--accent)] placeholder:text-ink-soft"/>
              <label className="h-10 px-3 rounded-xl border border-line bg-white flex items-center gap-1.5 text-[12px] font-bold acc-text cursor-pointer hover:border-[var(--accent)] transition-colors shrink-0">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12" strokeLinecap="round" strokeLinejoin="round"/></svg>
                {f.file ? f.file.slice(0,14) : 'Upload'}
                <input type="file" accept=".pdf" className="hidden" onChange={e=>{const x=e.target.files[0];if(!x)return;const n=[...eduFiles];n[i]={...n[i],file:x.name,url:''};setEduFiles(n);}}/>
              </label>
            </div>
          ))}
        </div>
        <p className="text-[11px] text-ink-muted mt-3">These appear as “User manual · Care guide · Our products” links in the customer funnel.</p>
        <datalist id="rb-video-taglines">{['How to use','Setup instructions','Unboxing','Care & maintenance','Troubleshooting'].map(t=><option key={t} value={t}/>)}</datalist>
        <datalist id="rb-edu-kinds">{['User manual','Care instructions','Product link','Warranty terms','Recipe book'].map(t=><option key={t} value={t}/>)}</datalist>
      </div>
    </div>
  );

  /* ══════════════════════════════════════════════════════
     STEP 3 — Preview
  ══════════════════════════════════════════════════════ */
  const Step3 = () => (
    <div className="grid lg:grid-cols-[1fr_300px] gap-8">
      {/* Left: summary + tags */}
      <div className="space-y-6">
        <div>
          <h4 className="text-[13px] font-bold text-ink mb-4">{ltype==='service'?'Service Summary':'Product Summary'} <span className="text-[11px] font-normal text-ink-muted ml-1">click a card to edit</span></h4>
          {image && <img src={image} alt="Product" className="w-16 h-16 rounded-xl object-cover border border-line mb-3"/>}
          <div className="grid grid-cols-2 gap-3 text-[13px]">
            {[
              { label:'Type',        val: ltype==='service'?'Service':'Product', go:1 },
              { label:'Name',        val: productName || '—', go:2 },
              { label:'Country',     val: country, go:1 },
              { label:'Marketplaces',val: selectedMktCount || '—', go:1 },
              { label:'Review Tags', val: tags.length || '—', go:2 },
              { label:'Videos & Guides', val: (videos.filter(v=>v.url||v.file).length + eduFiles.filter(f=>f.url||f.file).length) || '—', go:2 },
            ].map(row=>(
              <button key={row.label} onClick={()=>setStep(row.go)}
                className="group/sum text-left bg-surface-subtle hover:bg-white border border-transparent hover:border-line hover:shadow-soft rounded-xl px-4 py-3 transition-all">
                <p className="text-[11px] font-semibold text-ink-muted uppercase tracking-wide mb-1 flex items-center justify-between">{row.label}<span className="opacity-0 group-hover/sum:opacity-100 acc-text normal-case font-bold transition-opacity">Edit</span></p>
                <p className="font-bold text-ink">{row.val}</p>
              </button>
            ))}
          </div>
          {selectedMktCount > 0 && (
            <div className="flex flex-wrap gap-1.5 mt-3">
              {Object.keys(mkts).map(k=>{
                const m=MARKETPLACES.find(x=>x.k===k);
                if(!m) return null;
                const lbl = m.custom ? (customName.trim() || 'Custom marketplace') : m.label;
                return <span key={k} className="px-2.5 py-1 rounded-full text-[11px] font-bold acc-bg-soft acc-text">{lbl}</span>;
              })}
            </div>
          )}
        </div>

        {tags.length > 0 && (
          <div className="border-t border-line pt-6">
            <h4 className="text-[13px] font-bold text-ink mb-1">AI-Generated Review Tags</h4>
            <p className="text-[12px] text-ink-muted mb-3">Customers will tap these in the review widget.</p>
            <div className="flex flex-wrap gap-2">
              {tags.map((tag,i)=>(
                <span key={i} className="inline-flex items-center gap-1.5 px-3.5 py-1.5 rounded-full text-[12.5px] font-semibold acc-text acc-bg-soft border border-[var(--accent-50)]">
                  <svg width="9" height="9" viewBox="0 0 10 10" fill="none">
                    <path d="M1 4.5L1 7.5Q1 8.5 2 8.5L5.2 8.5Q5.8 8.5 6.4 7.8L8.5 5.5Q9 5 8.5 4.5L6.4 2.2Q5.8 1.5 5.2 1.5L2 1.5Q1 1.5 1 2.5Z" stroke="currentColor" strokeWidth="1" fill="none"/>
                    <circle cx="3.2" cy="4.5" r=".9" fill="currentColor"/>
                  </svg>
                  {tag}
                </span>
              ))}
            </div>
          </div>
        )}

        {bulletInputs.filter(Boolean).length > 0 && (
          <div className="border-t border-line pt-6">
            <h4 className="text-[13px] font-bold text-ink mb-3">Product Features</h4>
            <ul className="space-y-2">
              {bulletInputs.filter(Boolean).map((b,i)=>(
                <li key={i} className="flex items-start gap-2.5 text-[13px] text-ink-muted">
                  <span className="w-5 h-5 rounded-full acc-bg-soft acc-text flex items-center justify-center text-[10px] font-bold shrink-0 mt-0.5">{i+1}</span>
                  {b}
                </li>
              ))}
            </ul>
          </div>
        )}
      </div>

      {/* Right: widget preview */}
      <div>
        <p className="text-[10.5px] font-bold uppercase tracking-wider text-ink-muted mb-3">Customer Widget Preview</p>
        <div className="rounded-2xl overflow-hidden shadow-card border border-line bg-white">
          <div className="px-4 py-3 flex items-center gap-2" style={{background:'var(--sidebar-bg,#0E1A24)'}}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="white"><path d="M12 2l2.4 7.4H22l-6 4.4 2.3 7.2L12 16.7 5.7 21l2.3-7.2-6-4.4h7.6z"/></svg>
            <span className="text-white text-[11px] font-bold">ReviewBuddie</span>
          </div>
          <div className="p-5 space-y-4">
            <div className="flex items-center gap-3">
              {image && <img src={image} alt="" className="w-11 h-11 rounded-lg object-cover border border-line shrink-0"/>}
              <div>
                <p className="text-[10.5px] text-ink-muted">How was your experience with</p>
                <p className="text-[15px] font-bold text-ink mt-0.5 leading-tight">{productName || 'your product'}?</p>
              </div>
            </div>
            <div>
              <p className="text-[10.5px] font-semibold text-ink-muted mb-1.5">Overall Rating</p>
              <div className="flex gap-0.5">
                {[1,2,3,4,5].map(s=>(
                  <button key={s} onMouseEnter={()=>setHoverStars(s)} onMouseLeave={()=>setHoverStars(0)} onClick={()=>setWidgetStars(s)}
                    className="text-[26px] leading-none transition-transform hover:scale-110">
                    <span style={{color:s<=(hoverStars||widgetStars)?'#F59E0B':'#E2E8F0'}}>★</span>
                  </button>
                ))}
              </div>
            </div>
            <div>
              <p className="text-[10.5px] font-semibold text-ink-muted mb-2">What stood out?</p>
              <div className="flex flex-wrap gap-1.5">
                {(tags.length ? tags : ['Build Quality','Battery Life','Camera']).map((tag,i)=>(
                  <button key={i} onClick={()=>tags.length&&toggleTag(tag)}
                    className={"px-2.5 py-1 rounded-full text-[11px] font-semibold border transition-all " +
                      (selectedTags.includes(tag) ? 'acc-bg text-white border-transparent'
                        : tags.length ? 'bg-white border-gray-200 text-ink-muted hover:border-[var(--accent)]'
                        : 'bg-surface-subtle border-gray-100 text-gray-300 cursor-default')}>
                    {tag}
                  </button>
                ))}
                {!tags.length && <p className="w-full text-[10px] text-slate-400 mt-0.5">Placeholder — your tags appear here</p>}
              </div>
            </div>
            <textarea rows={2} placeholder="Anything else? (optional)"
              className="w-full bg-surface-subtle rounded-lg px-3 py-2 text-[11px] text-ink placeholder:text-slate-400 outline-none resize-none border border-gray-100"/>
            <button className="w-full py-2.5 rounded-xl text-[12.5px] font-bold text-white"
              style={{background:'linear-gradient(135deg,var(--accent),var(--accent-dark))'}}>
              Submit Review
            </button>
          </div>
        </div>
      </div>
    </div>
  );

  /* ══ Render ══ */
  return (
    <>
      <PageHeader crumbs={['Products','Add Product']} title="Add New Product"
        action={
          step === 3
            ? <BtnPrimary onClick={()=>onNav('products')}>Publish Product</BtnPrimary>
            : <BtnGhost>Save Draft</BtnGhost>
        }/>

      <div className="px-7 py-6 space-y-6">
        {/* Stepper */}
        <div className="flex items-center">
          {STEPS.map((s,i)=>(
            <React.Fragment key={s.n}>
              <div className="flex flex-col items-center gap-1.5 shrink-0">
                <div className={"w-8 h-8 rounded-full flex items-center justify-center text-[13px] font-bold transition-all " +
                  (step===s.n ? 'acc-bg text-white shadow-btn' : step>s.n ? 'acc-bg-soft acc-text' : 'bg-gray-100 text-ink-muted')}>
                  {step>s.n
                    ? <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M2.5 7l3 3 6-6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
                    : s.n}
                </div>
                <span className={"text-[11.5px] font-semibold whitespace-nowrap " + (step===s.n?'acc-text':'text-ink-muted')}>{s.label}</span>
              </div>
              {i<STEPS.length-1 && (
                <div className={"flex-1 h-0.5 mx-4 mb-5 rounded-full transition-all " + (step>s.n?'acc-bg':'bg-gray-200')}/>
              )}
            </React.Fragment>
          ))}
        </div>

        {/* Step card */}
        <Card className="p-6">
          {step===1 && Step1()}
          {step===2 && Step2()}
          {step===3 && Step3()}
        </Card>

        {/* Navigation */}
        <div className="flex items-center justify-between">
          {step > 1
            ? <BtnGhost onClick={()=>setStep(s=>s-1)}>← Back</BtnGhost>
            : <div/>}
          {step < 3
            ? <div className="flex items-center gap-3">
                {!canNext && !generating && (
                  <span className="text-[12px] text-ink-soft">{step===1 ? 'Select at least one marketplace to continue' : 'Enter a product name to continue'}</span>
                )}
                <button
                  onClick={step===2 ? goToPreview : ()=>setStep(s=>s+1)}
                  disabled={generating || !canNext}
                  className="inline-flex items-center gap-2 px-6 py-2.5 rounded-xl text-[13px] font-semibold text-white transition-all disabled:opacity-60 disabled:cursor-not-allowed shadow-btn"
                  style={{background:'linear-gradient(135deg,var(--accent),var(--accent-dark))'}}>
                  {generating
                    ? <><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" style={{animation:'rCW 0.9s linear infinite',transformOrigin:'center'}}><path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/></svg>Generating tags…</>
                    : <>Next →</>}
                </button>
              </div>
            : <BtnPrimary onClick={()=>onNav('products')}>Publish Product</BtnPrimary>
          }
        </div>
      </div>
    </>
  );
}

/* ── CREATE PROMOTION ──────────────────────────────────────────────────────── */
const PROMO_TYPES = [
  'Warranty','Extended Warranty','Cashback','Coupon code',
  'Gift Card','Product Information','Digital Download','Product Giveaway'
];

const TYPE_TO_PROMO_IDX = {
  'Warranty':0, 'Extended Warranty':1, 'Cashback':2, 'Coupon code':3,
  'Gift Card':4, 'Product Information':5, 'Digital Download':6, 'Product Giveaway':3,
};

/* ── CLAIM FULFILLMENT — what we collect from the customer to deliver the reward ─ */
const RB_MARKETS = ['India','United States','United Kingdom','Europe (EU)','Canada','Australia','UAE','Global / Other'];
const RB_PAYOUTS = {
  'India':[{id:'upi',lb:'UPI ID',hint:'name@bank'},{id:'gpay-in',lb:'GPay',hint:'mobile number'},{id:'amazonpay-in',lb:'Amazon Pay balance',hint:'mobile / email'}],
  'United States':[{id:'paypal',lb:'PayPal',hint:'email'},{id:'venmo',lb:'Venmo',hint:'@username'},{id:'zelle',lb:'Zelle',hint:'email / mobile'},{id:'cashapp',lb:'Cash App',hint:'$Cashtag'},{id:'giftcard-us',lb:'Amazon gift card',hint:'email'}],
  'United Kingdom':[{id:'paypal',lb:'PayPal',hint:'email'},{id:'bank-uk',lb:'Bank transfer',hint:'sort code + account no.'},{id:'revolut-uk',lb:'Revolut',hint:'@revtag / mobile'},{id:'giftcard-uk',lb:'Amazon gift card',hint:'email'}],
  'Europe (EU)':[{id:'paypal',lb:'PayPal',hint:'email'},{id:'sepa',lb:'SEPA transfer',hint:'IBAN'},{id:'revolut-eu',lb:'Revolut',hint:'@revtag / mobile'},{id:'giftcard-eu',lb:'Amazon gift card',hint:'email'}],
  'Canada':[{id:'paypal',lb:'PayPal',hint:'email'},{id:'interac',lb:'Interac e-Transfer',hint:'email'},{id:'giftcard-ca',lb:'Amazon gift card',hint:'email'}],
  'Australia':[{id:'paypal',lb:'PayPal',hint:'email'},{id:'payid',lb:'PayID',hint:'mobile / email'},{id:'giftcard-au',lb:'Amazon gift card',hint:'email'}],
  'UAE':[{id:'bank-ae',lb:'Bank transfer',hint:'IBAN'},{id:'paypal',lb:'PayPal',hint:'email'},{id:'giftcard-ae',lb:'Amazon.ae gift card',hint:'email'}],
  'Global / Other':[{id:'paypal',lb:'PayPal',hint:'email'},{id:'wise',lb:'Wise',hint:'email'},{id:'giftcard-gl',lb:'Amazon gift card',hint:'email'}],
};
/* per-type: what the claim page will ask the customer for */
const RB_FULFIL = {
  'Cashback':          { kind:'payout', note:'Customer picks any ONE of the payout options you enable below and fills in just that detail — you send the cashback there after approving the claim.', delivery:['Customer submits claim with their chosen payout detail','You approve the claim in Claim Center','Cashback is sent to their UPI / PayPal / bank within 24–48 hrs'] },
  'Gift Card':         { kind:'email',  fields:['Email address'], note:'Gift-card code is emailed to the customer after approval.', delivery:['Customer submits claim with their email','You approve the claim in Claim Center','Gift-card code is emailed automatically'] },
  'Coupon code':       { kind:'none',   fields:['Email address (optional)'], note:'Coupon code is shown on-screen instantly — no payout details needed.', delivery:['Customer completes the claim page','Coupon code appears on-screen instantly (and by email if provided)','Customer redeems it at checkout'] },
  'Warranty':          { kind:'auto',   fields:['Order ID','Email address'], note:'Auto-approved — warranty certificate is emailed instantly.', delivery:['Customer submits Order ID + email','Claim auto-approves — no action needed from you','Warranty certificate is emailed instantly'] },
  'Extended Warranty': { kind:'auto',   fields:['Order ID','Email address'], note:'Auto-approved — warranty certificate is emailed instantly.', delivery:['Customer submits Order ID + email','Claim auto-approves — no action needed from you','Warranty certificate is emailed instantly'] },
  'Digital Download':  { kind:'email', upload:true, fields:['Email address'], note:'Download link is emailed after approval. Upload the file customers will receive.', delivery:['Customer submits claim with their email','You approve the claim in Claim Center','Secure download link is emailed automatically'] },
  'Product Information':{kind:'content', fields:[], note:'Informational only — nothing is collected from the customer. Choose how the product information is delivered on the claim page.', delivery:['Customer scans the QR on your insert','Content opens directly on the claim page — no approval needed'] },
  'Product Giveaway':  { kind:'ship',   fields:['Full name','Shipping address','Phone number'], note:'The claim page will ask the customer for their shipping address — you ship the free product to the address they provide.', delivery:['Customer submits claim with shipping details','You approve the claim in Claim Center','You ship the free product and mark it delivered'] },
};
const RB_CONTENT = [
  {id:'file',  lb:'File upload',  hint:'PDF · guide'},
  {id:'video', lb:'Video upload', hint:'MP4 · 200 MB'},
  {id:'yt',    lb:'YouTube link', hint:'Embedded'},
];
function FulfillmentSection({ type, market, setMarket, methods, setMethods, orderIdMode, setOrderIdMode, ltype='product' }) {
  const svc = ltype==='service';
  let cfg = RB_FULFIL[type] || RB_FULFIL['Coupon code'];
  if (svc && type==='Product Giveaway') cfg = {...cfg, fields:['Full name','Phone number','Preferred date & time'], note:'The claim page will ask the customer for their contact and preferred slot \u2014 you schedule the free service with them.', delivery:['Customer submits claim with contact + preferred slot','You approve the claim in Claim Center','You schedule and deliver the free service, then mark it delivered']};
  if (svc && (type==='Warranty'||type==='Extended Warranty')) cfg = {...cfg, note:'Auto-approved \u2014 service guarantee certificate is emailed instantly (e.g. free re-service within 30 days).', delivery:['Customer submits Booking ID + email','Claim auto-approves \u2014 no action needed from you','Service guarantee certificate is emailed instantly']};
  const payouts = RB_PAYOUTS[market] || RB_PAYOUTS['Global / Other'];
  const toggle = id => setMethods(m => m.includes(id) ? m.filter(x=>x!==id) : [...m, id]);
  const [content, setContent] = React.useState(['file']);
  const [ytUrl, setYtUrl] = React.useState('');
  const toggleContent = id => setContent(c => c.includes(id) ? c.filter(x=>x!==id) : [...c, id]);
  const [redeemLink, setRedeemLink] = React.useState('');
  const [redeemSteps, setRedeemSteps] = React.useState('');
  const idLb = svc ? 'Booking / Invoice ID' : 'Order ID';
  const oid = orderIdMode==='required' ? idLb : idLb+' (optional)';
  const asked = [...new Set(cfg.kind==='payout'
    ? [oid,'Email address', ...payouts.filter(p=>methods.includes(p.id)).map(p=>p.lb)].map((f,i)=>i>1?f+' (any one)':f)
    : [oid, ...(cfg.fields||[]).filter(f=>f!=='Order ID')])];
  return (
    <div className="rounded-xl border border-line bg-surface-subtle/60 p-4 space-y-3">
      <div className="flex items-center justify-between gap-3 flex-wrap">
        <span className="text-[13px] font-bold text-ink">Claim fulfillment</span>
        <span className="text-[11px] font-bold px-2 py-0.5 rounded-full bg-brand-50 text-brand">{type}</span>
      </div>
      <p className="text-[12px] text-ink-muted leading-relaxed">{cfg.note}</p>
      {cfg.delivery && (
        <div className="bg-white border border-line rounded-lg px-3.5 py-3">
          <span className="block text-[11px] font-bold uppercase tracking-wider text-ink-muted mb-2">How it's delivered</span>
          <ol className="space-y-1.5">
            {cfg.delivery.map((s,i)=>(
              <li key={i} className="flex items-start gap-2 text-[12px] text-ink">
                <span className="shrink-0 w-4.5 h-4.5 min-w-[18px] h-[18px] rounded-full bg-brand-50 text-brand text-[10px] font-extrabold flex items-center justify-center mt-px">{i+1}</span>
                {s}
              </li>
            ))}
          </ol>
        </div>
      )}
      <div className="flex items-center justify-between gap-3 bg-white border border-line rounded-lg px-3 py-2.5">
        <div>
          <span className="block text-[12px] font-semibold text-ink">Require {svc?'Booking / Invoice ID':'Order ID'}</span>
          <span className="block text-[11px] text-ink-muted">Off = customers can skip it on the claim page</span>
        </div>
        <StatusToggle checked={orderIdMode==='required'} onChange={()=>setOrderIdMode(m=>m==='required'?'optional':'required')}/>
      </div>
      {cfg.kind==='payout' && (<>
        <Field label="Customer market" hint="Sets which payout options customers can choose">
          <Select value={market} onChange={e=>{setMarket(e.target.value); setMethods((RB_PAYOUTS[e.target.value]||[]).slice(0,1).map(p=>p.id));}}>
            {RB_MARKETS.map(m=><option key={m}>{m}</option>)}
          </Select>
        </Field>
        <div>
          <span className="block text-[12px] font-semibold text-ink mb-1.5">Payout options offered <span className="text-rose-500">*</span> <span className="font-normal text-ink-soft">— customer chooses one</span></span>
          <div className="flex flex-wrap gap-2">
            {payouts.map(p => {
              const on = methods.includes(p.id);
              return (
                <button type="button" key={p.id} onClick={()=>toggle(p.id)}
                  className={"inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-[12px] font-bold border transition-colors "+(on?"bg-brand text-white border-brand":"bg-white text-ink-muted border-line hover:border-brand-200")}>
                  {on && <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M20 6L9 17l-5-5"/></svg>}
                  {p.lb}{p.hint && <span className={on?"text-white/70 font-medium":"text-ink-soft font-medium"}>· {p.hint}</span>}
                </button>
              );
            })}
          </div>
          {methods.length===0 && <p className="text-[11px] text-rose-500 font-semibold mt-1.5">Select at least one payout method.</p>}
        </div>
      </>)}
      {cfg.upload && (
        <div>
          <span className="block text-[12px] font-semibold text-ink mb-1.5">Download file <span className="text-rose-500">*</span> <span className="font-normal text-ink-soft">— sent to the customer after approval</span></span>
          <div className="rounded-lg border-2 border-dashed border-brand/40 bg-white py-4 text-center">
            <p className="text-[12px] text-ink-muted">Drag your file here or <a className="text-brand font-semibold cursor-pointer">browse</a> <span className="text-ink-soft">— PDF, ZIP, EPUB · up to 100 MB</span></p>
          </div>
        </div>
      )}
      {cfg.kind==='content' && (
        <div>
          <span className="block text-[12px] font-semibold text-ink mb-1.5">Content delivered to the customer <span className="text-rose-500">*</span> <span className="font-normal text-ink-soft">— pick one or more</span></span>
          <div className="flex flex-wrap gap-2">
            {RB_CONTENT.map(p => {
              const on = content.includes(p.id);
              return (
                <button type="button" key={p.id} onClick={()=>toggleContent(p.id)}
                  className={"inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-[12px] font-bold border transition-colors whitespace-nowrap "+(on?"bg-brand text-white border-brand":"bg-white text-ink-muted border-line hover:border-brand-200")}>
                  {on && <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M20 6L9 17l-5-5"/></svg>}
                  {p.lb}<span className={on?"text-white/70 font-medium":"text-ink-soft font-medium"}>· {p.hint}</span>
                </button>
              );
            })}
          </div>
          {content.includes('file') && (
            <div className="mt-3 rounded-lg border-2 border-dashed border-brand/40 bg-white py-4 text-center">
              <p className="text-[12px] text-ink-muted">Drag your file here or <a className="text-brand font-semibold cursor-pointer">browse</a> <span className="text-ink-soft">— PDF, DOCX, images</span></p>
            </div>
          )}
          {content.includes('video') && (
            <div className="mt-3 rounded-lg border-2 border-dashed border-brand/40 bg-white py-4 text-center">
              <p className="text-[12px] text-ink-muted">Drag your video here or <a className="text-brand font-semibold cursor-pointer">browse</a> <span className="text-ink-soft">— MP4 · MOV, up to 200 MB</span></p>
            </div>
          )}
          {content.includes('yt') && (
            <div className="mt-3">
              <Input placeholder="https://youtube.com/watch?v=…" value={ytUrl} onChange={e=>setYtUrl(e.target.value)}/>
            </div>
          )}
          {content.length===0 && <p className="text-[11px] text-rose-500 font-semibold mt-1.5">Select at least one content type.</p>}
        </div>
      )}
      {type==='Coupon code' && (
        <div className="bg-white border border-line rounded-lg px-3.5 py-3 space-y-3">
          <span className="block text-[11px] font-bold uppercase tracking-wider text-ink-muted">Redemption details <span className="font-semibold normal-case tracking-normal text-ink-soft">— optional, shown with the coupon</span></span>
          <Field label="Redemption link">
            <Input placeholder="Eg. www.yourstore.com/checkout" value={redeemLink} onChange={e=>setRedeemLink(e.target.value)}/>
          </Field>
          <Field label="Steps to redeem">
            <textarea rows="3" placeholder={"Eg.\n1. Add the product to your cart\n2. Paste the code at checkout\n3. Discount applies instantly"} value={redeemSteps} onChange={e=>setRedeemSteps(e.target.value)}
              className="w-full bg-surface-input rounded-xl px-3.5 py-2.5 text-[13px] text-ink placeholder:text-ink-soft outline-none focus:ring-2 focus:ring-brand-200 resize-y"></textarea>
          </Field>
        </div>
      )}
      <div className="pt-2 border-t border-line/70">
        <span className="block text-[11px] font-bold uppercase tracking-wider text-ink-muted mb-1.5">Claim page will ask for</span>
        <div className="flex flex-wrap gap-1.5">
          {asked.length ? asked.map(f=><span key={f} className="text-[11px] font-semibold px-2 py-1 rounded-md bg-white border border-line text-ink-muted">{f}</span>)
            : <span className="text-[11px] text-ink-soft">Nothing — informational promotion</span>}
        </div>
      </div>
    </div>
  );
}

function CreatePromotion({ ctx, layout = 'Standard' }) {
  const PD = window.PROMOS_DATA || [];
  const getTH = () => window.TH_DATA || [];

  const initType = ctx?.type || 'Warranty';
  const initIdx  = TYPE_TO_PROMO_IDX[initType] ?? 0;
  const initPD   = PD[initIdx] || {};

  const [type,      setType]      = React.useState(initType);
  const [name,      setName]      = React.useState('');
  const [title,     setTitle]     = React.useState(initPD.copies?.[0]?.t || '');
  const [desc,      setDesc]      = React.useState(initPD.copies?.[0]?.s || '');
  const [features,  setFeatures]  = React.useState((initPD.pills || []).slice(0,3).map(p=>p.lb));
  const [themeIdx,  setThemeIdx]  = React.useState(initPD.th ?? 0);
  const [animIdx,   setAnimIdx]   = React.useState(0);
  const [ctaText,   setCtaText]   = React.useState('');
  const [market,    setMarket]    = React.useState('India');
  const [methods,   setMethods]   = React.useState(['upi']);
  const [orderIdMode, setOrderIdMode] = React.useState('required');
  const [ltype, setLtype] = React.useState('product');   // product | service
  const [brand,     setBrand]     = React.useState((window.RB_BRANDS||[{name:'Brontix'}])[0]?.name || 'Brontix');

  const promoIdx = TYPE_TO_PROMO_IDX[type] ?? 0;
  const pd       = PD[promoIdx] || {};
  const themes   = getTH();
  const valid    = name.trim().length > 0;

  /* Reset card content when promotion type changes */
  React.useEffect(() => {
    const idx = TYPE_TO_PROMO_IDX[type] ?? 0;
    const p   = (window.PROMOS_DATA || [])[idx] || {};
    setTitle(p.copies?.[0]?.t || '');
    setDesc(p.copies?.[0]?.s  || '');
    setFeatures((p.pills || []).slice(0,3).map(x=>x.lb));
    setThemeIdx(p.th ?? 0);
    setAnimIdx(0);
  }, [type]);

  const updateFeature = (i, val) => {
    const nf = [...features]; nf[i] = val; setFeatures(nf);
  };

  /* helpers: does current text exactly match a preset? */
  const titlePresetVal = (pd.copies||[]).some(cp=>cp.t===title) ? title : '__custom__';
  const descPresetVal  = (pd.copies||[]).some(cp=>cp.s===desc)  ? desc  : '__custom__';

  /* ── Clean (canvas) layout ─────────────────────────────────────── */
  if (layout === 'Clean') return (
    <>
      <PageHeader crumbs={['Promotions','Create Promotion']} title="Create Promotion"/>
      <div className="px-7 py-6 flex flex-col gap-5">

        {/* Top bar: name · type · theme · create */}
        <div className="flex items-center gap-3 flex-wrap bg-white border border-line rounded-2xl px-5 py-3 shadow-soft">
          <Input placeholder="Promotion name" value={name} onChange={e=>setName(e.target.value)}
            className="w-52"/>
          <Select value={type} onChange={e=>setType(e.target.value)} className="w-44">
            {PROMO_TYPES.map(pt=><option key={pt}>{pt}</option>)}
          </Select>
          <Select value={brand} onChange={e=>setBrand(e.target.value)} className="w-36" title="Brand">
            {(window.RB_BRANDS || [{name:'Brontix'}]).map(b=><option key={b.name}>{b.name}</option>)}
            <option value="__none__">Don't show a brand</option>
          </Select>
          <div className="h-5 w-px bg-line mx-1"></div>
          <div className="flex items-center gap-2">
            {themes.map((th,i)=>(
              <button key={i} onClick={()=>setThemeIdx(i)} title={th.n}
                style={{width:20,height:20,borderRadius:'50%',background:th.c,border:'none',cursor:'pointer',flexShrink:0,
                  boxShadow: i===themeIdx ? `0 0 0 2px white, 0 0 0 3.5px ${th.c}` : 'none',transition:'box-shadow .15s'}}/>
            ))}
          </div>
          <div className="flex-1"></div>
          <BtnPrimary disabled={!valid}>Create Promotion</BtnPrimary>
        </div>

        {/* Controls + Card */}
        <div className="flex gap-6 items-start">

          {/* Controls column */}
          <div className="flex-1 min-w-0 flex flex-col gap-4">

            {/* Title */}
            <div>
              <label className="text-[11px] font-bold uppercase tracking-wider text-ink-muted block mb-1.5">
                Title <span className="normal-case font-normal text-ink-soft ml-1">· pick a suggestion or write your own · wrap *word* in asterisks</span>
              </label>
              <ComboText placeholder="e.g. Secure Your *Purchase!*" value={title} onChange={setTitle} options={(pd.copies||[]).map(cp=>cp.t)}/>
            </div>

            {/* Subtitle */}
            <div>
              <label className="text-[11px] font-bold uppercase tracking-wider text-ink-muted block mb-1.5">Subtitle</label>
              <ComboText placeholder="Supporting line… wrap *key word* in asterisks" value={desc} onChange={setDesc} options={(pd.copies||[]).map(cp=>cp.s)}/>
            </div>

            {/* CTA */}
            <div>
              <label className="text-[11px] font-bold uppercase tracking-wider text-ink-muted block mb-1.5">CTA button text</label>
              <ComboText placeholder={pd.cta || 'Claim My Warranty'} value={ctaText} onChange={setCtaText} options={(window.RB_CTA_OPTIONS||{})[type] || []}/>
            </div>

            {/* Animation */}
            <div>
              <label className="text-[11px] font-bold uppercase tracking-wider text-ink-muted block mb-1.5">Animation</label>
              {typeof AnimPicker !== 'undefined' && (
                <AnimPicker promoIdx={promoIdx} themeIdx={themeIdx} value={animIdx} onChange={setAnimIdx}/>
              )}
            </div>

            {/* Feature pills */}
            <div>
              <label className="text-[11px] font-bold uppercase tracking-wider text-ink-muted block mb-1.5">Feature Pills</label>
              <div className="grid grid-cols-3 gap-2">
                {[0,1,2].map(i=>(
                  <Input key={i} placeholder={(pd.pills?.[i]?.lb)||('Feature '+(i+1))}
                    value={features[i]||''} onChange={e=>updateFeature(i,e.target.value)}/>
                ))}
              </div>
            </div>

            <div className="flex items-center gap-2">
              <span className="text-[12px] font-semibold text-ink-muted">This promotion is for :</span>
              {[['product','Product'],['service','Service']].map(([id,lb])=>(
                <button type="button" key={id} onClick={()=>setLtype(id)}
                  className={"px-3 py-1.5 rounded-full text-[12px] font-bold border transition-colors "+(ltype===id?"bg-brand text-white border-brand":"bg-white text-ink-muted border-line hover:border-brand-200")}>{lb}</button>
              ))}
            </div>
            <FulfillmentSection type={type} market={market} setMarket={setMarket} methods={methods} setMethods={setMethods} orderIdMode={orderIdMode} setOrderIdMode={setOrderIdMode} ltype={ltype}/>

          </div>

          {/* Live card — fixed 360px, right side */}
          <div className="shrink-0" style={{width:360}}>
            {typeof PromoCard !== 'undefined' && (
              <PromoCard promoIdx={promoIdx} themeIdx={themeIdx} animIdx={animIdx} brand={brand}
                title={title} subtitle={desc} features={features} cta={ctaText}/>
            )}
          </div>
        </div>
      </div>
    </>
  );

  return (
    <>
      <PageHeader crumbs={['Promotions','Create Promotion']} title="Create Promotion"/>
      <div className="px-7 py-6 grid lg:grid-cols-[1fr_360px] gap-6 items-start">

        {/* ── Left: form ── */}
        <Card className="p-6 space-y-5">

          {/* Type + Name + Brand — two columns */}
          <div className="grid sm:grid-cols-2 gap-4">
            <Field label="Promotion Name" required hint="Internal — not shown to customers">
              <Input placeholder="Enter promotion name" value={name} onChange={e=>setName(e.target.value)}/>
            </Field>
            <Field label="Promotion Type" required>
              <Select value={type} onChange={e=>setType(e.target.value)}>
                {PROMO_TYPES.map(t => <option key={t}>{t}</option>)}
              </Select>
            </Field>
            <Field label="Brand" required hint="Shown on the claim page · manage in Settings → Brand Details">
              <Select value={brand} onChange={e=>setBrand(e.target.value)}>
                {(window.RB_BRANDS || [{name:'Brontix'}]).map(b => <option key={b.name}>{b.name}</option>)}
                <option value="__none__">Don't show a brand</option>
              </Select>
            </Field>
          </div>

          {/* Title */}
          <div>
            <label className="block text-[13px] font-semibold text-ink mb-1.5">
              Title <span className="text-rose-500">*</span>
              <span className="ml-1.5 text-[11px] font-normal text-ink-muted">pick a suggestion or write your own · wrap a *word* in asterisks to accent-colour it</span>
            </label>
            <ComboText placeholder="e.g. Secure Your *Purchase!*" value={title} onChange={setTitle} options={(pd.copies||[]).map(cp=>cp.t)}/>
          </div>

          {/* Animation picker — below title */}
          {typeof AnimPicker !== 'undefined' && (
            <div>
              <span className="block text-[13px] font-semibold text-ink mb-2">Animation</span>
              <AnimPicker
                promoIdx={promoIdx}
                themeIdx={themeIdx}
                value={animIdx}
                onChange={setAnimIdx}
              />
            </div>
          )}

          {/* Subtitle */}
          <div>
            <label className="block text-[13px] font-semibold text-ink mb-1.5">Subtitle</label>
            <ComboText placeholder="Supporting line… wrap *key word* in asterisks" value={desc} onChange={setDesc} options={(pd.copies||[]).map(cp=>cp.s)}/>
          </div>

          {/* CTA button text */}
          <div>
            <label className="block text-[13px] font-semibold text-ink mb-1.5">CTA button text</label>
            <ComboText placeholder={pd.cta || 'Claim My Warranty'} value={ctaText} onChange={setCtaText} options={(window.RB_CTA_OPTIONS||{})[type] || []}/>
          </div>

          {/* Feature pills */}
          <div>
            <span className="block text-[13px] font-semibold text-ink mb-1.5">Feature Pills</span>
            <div className="grid grid-cols-3 gap-2">
              {[0,1,2].map(i => (
                <Input key={i}
                  placeholder={(pd.pills?.[i]?.lb) || ('Feature ' + (i+1))}
                  value={features[i] || ''}
                  onChange={e => updateFeature(i, e.target.value)}/>
              ))}
            </div>
          </div>

          <div className="flex items-center gap-2">
              <span className="text-[12px] font-semibold text-ink-muted">This promotion is for :</span>
              {[['product','Product'],['service','Service']].map(([id,lb])=>(
                <button type="button" key={id} onClick={()=>setLtype(id)}
                  className={"px-3 py-1.5 rounded-full text-[12px] font-bold border transition-colors "+(ltype===id?"bg-brand text-white border-brand":"bg-white text-ink-muted border-line hover:border-brand-200")}>{lb}</button>
              ))}
            </div>
            <FulfillmentSection type={type} market={market} setMarket={setMarket} methods={methods} setMethods={setMethods} orderIdMode={orderIdMode} setOrderIdMode={setOrderIdMode} ltype={ltype}/>

          <div className="pt-2">
            <BtnPrimary disabled={!valid || (RB_FULFIL[type]?.kind==='payout' && methods.length===0)}>Create Promotion</BtnPrimary>
          </div>
        </Card>

        {/* ── Right: live card preview ── */}
        <div className="lg:sticky lg:top-6 flex flex-col gap-4">

          {/* Theme dots */}
          <div className="bg-white rounded-xl border border-line shadow-soft px-4 py-3 flex items-center gap-3 flex-wrap">
            <span className="text-[10.5px] font-bold uppercase tracking-wider text-ink-muted shrink-0">Theme</span>
            <div className="flex gap-2 flex-wrap">
              {themes.map((t, i) => (
                <button key={i} onClick={() => setThemeIdx(i)}
                  title={t.n}
                  style={{
                    width:22, height:22, borderRadius:'50%', background:t.c,
                    border:'none', cursor:'pointer', flexShrink:0, transition:'box-shadow .15s',
                    boxShadow: i===themeIdx ? `0 0 0 2.5px white, 0 0 0 4.5px ${t.c}` : 'none',
                  }}/>
              ))}
            </div>
          </div>

          {/* Card */}
          {typeof PromoCard !== 'undefined' && (
            <PromoCard
              promoIdx={promoIdx}
              themeIdx={themeIdx}
              animIdx={animIdx}
              brand={brand}
              title={title}
              subtitle={desc}
              features={features}
              cta={ctaText}
            />
          )}






        </div>
      </div>
    </>
  );
}

const PromoStockImg = ({ kind }) => {
  const map = {
    'shield': <svg viewBox="0 0 48 48" width="40" height="40"><defs><linearGradient id="psg1" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stopColor="#60A5FA"/><stop offset="1" stopColor="#1D4ED8"/></linearGradient></defs><path d="M24 6 L40 12 V24 C40 34 32 40 24 42 C16 40 8 34 8 24 V12 Z" fill="url(#psg1)"/><path d="M16 23 L21 28 L33 16" stroke="#fff" strokeWidth="3.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>,
    'star-seal': <svg viewBox="0 0 48 48" width="40" height="40"><circle cx="24" cy="24" r="16" fill="#FBBF24"/><path d="M24 12l3 8 8 1-6 5 2 8-7-4-7 4 2-8-6-5 8-1z" fill="#FFF8E1"/><path d="M12 38l3-4 4 4M36 38l-3-4-4 4" stroke="#F59E0B" strokeWidth="3" fill="none" strokeLinecap="round"/></svg>,
    'trophy': <svg viewBox="0 0 48 48" width="40" height="40"><path d="M12 8h24v10c0 8-6 14-12 14s-12-6-12-14V8z" fill="#92400E"/><path d="M16 12h16v6c0 6-4 10-8 10s-8-4-8-10v-6z" fill="#F59E0B"/><path d="M22 26h4v8h-4z" fill="#92400E"/><path d="M16 36h16v4H16z" fill="#92400E"/><path d="M20 22l2 3 5-5" stroke="#fff" strokeWidth="2.2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>,
    'badge': <svg viewBox="0 0 48 48" width="40" height="40"><path d="M24 6 L40 12 V24 C40 34 32 40 24 42 C16 40 8 34 8 24 V12 Z" fill="#0EA5E9"/><circle cx="24" cy="22" r="8" fill="#FFF"/><path d="M20 22l3 3 5-6" stroke="#0EA5E9" strokeWidth="2.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/><path d="M24 30v8" stroke="#FBBF24" strokeWidth="4" strokeLinecap="round"/></svg>,
    'coupon-stock':  <svg viewBox="0 0 60 40" width="40" height="40"><path d="M2 10 H58 V15 a5 5 0 0 0 0 10 V30 H2 V25 a5 5 0 0 0 0 -10 Z" fill="#0096DB"/><line x1="30" y1="12" x2="30" y2="28" stroke="white" strokeDasharray="2 2"/><circle cx="42" cy="20" r="4" fill="white"/><path d="M38 24 L46 16" stroke="#0096DB" strokeWidth="1.6"/></svg>,
  };
  return map[kind] || map['shield'];
};

function PromoPreviewScreen({ title, desc, imgKind }) {
  return (
    <div className="flex flex-col h-full">
      <div className="h-7"></div>
      <div className="flex items-center justify-center gap-1.5 py-3 border-b border-gray-100">
        <span className="text-[10px] font-bold text-ink-muted">⚡ Brontix</span>
      </div>
      <div className="flex-1 flex flex-col items-center justify-center px-5 text-center">
        <h3 className="text-[15px] font-bold text-ink leading-tight max-w-[180px]">{title}</h3>
        <p className="text-[10px] text-ink-muted mt-2 leading-snug">{desc}</p>
        <div className="my-5 w-[110px] h-[80px] rounded-lg bg-brand/20 flex items-center justify-center">
          <PromoStockImg kind="coupon-stock"/>
        </div>
        <button className="w-full bg-brand-200 text-brand-dark rounded-full py-2.5 font-semibold text-[12px]">
          Extend
        </button>
      </div>
    </div>
  );
}

/* ── ADD CAMPAIGN ──────────────────────────────────────────────────────────── */
function AddCampaign() {
  const [name, setName] = React.useState('');
  return (
    <>
      <PageHeader crumbs={['Campaigns','Add Campaign']} title="Add New Campaign"/>
      <div className="px-7 py-6 grid lg:grid-cols-[1fr_320px] gap-6 items-start">
        <Card className="p-6 space-y-5">
          <h3 className="text-[14px] font-bold text-ink">Campaign Details</h3>
          <Field label="Campaign Name" required>
            <Input placeholder="Enter campaign name" value={name} onChange={e=>setName(e.target.value)}/>
          </Field>
          <Field label="Promotion" required hint="Choose the promotion for this campaign">
            <Select defaultValue=""><option value="" disabled>Select promotion title</option><option>SPAIN</option><option>Cashback Test - Husain</option></Select>
          </Field>
          <Field label="Brand" required hint="Choose the brand for this campaign">
            <Select defaultValue=""><option value="" disabled>Select a your brand</option><option>Brontix</option></Select>
          </Field>
          <Field label="Products" required hint="Choose your products to be included in this campaign">
            <Select defaultValue=""><option value="" disabled>Select the product(s)</option><option>FRANCE</option><option>ITALY PRODUCT</option></Select>
          </Field>
          <div>
            <BtnPrimary disabled={!name.trim()}>Create Campaign</BtnPrimary>
          </div>
        </Card>

        <div className="lg:sticky lg:top-6">
          <PhonePreview>
            <div className="flex-1 flex flex-col items-center justify-center px-5 text-center pt-12">
              <h3 className="text-[15px] font-bold text-ink leading-tight">Extend Your<br/>Protection!</h3>
              <div className="my-5 w-[100px] h-[70px] rounded-lg bg-brand/20 flex items-center justify-center">
                <PromoStockImg kind="coupon-stock"/>
              </div>
              <button className="w-full bg-brand text-white rounded-full py-2.5 font-semibold text-[12px]">Extend</button>
            </div>
          </PhonePreview>
        </div>
      </div>
    </>
  );
}

/* ── PACKAGE INSERTS ───────────────────────────────────────────────────────── */
/* decorative branded QR — deterministic fake module pattern, real gen wired later */
function BrandedQR({ size=112, color='#1B2733', dot='square', logo=true, frame, frameColor }) {
  const N=21, cell=size/N, mods=[];
  const inEye=(r,c)=>(r<7&&c<7)||(r<7&&c>=N-7)||(r>=N-7&&c<7);
  const inLogo=(r,c)=>logo && r>=8&&r<=12&&c>=8&&c<=12;
  for(let r=0;r<N;r++)for(let c=0;c<N;c++){
    if(inEye(r,c)||inLogo(r,c))continue;
    if(((r*31+c*17+r*c)%5)<2) mods.push([r,c]);
  }
  const eye=(x,y)=>(
    <g key={x+'-'+y}>
      <rect x={x*cell} y={y*cell} width={cell*7} height={cell*7} rx={dot==='square'?0:cell*1.6} fill="none" stroke={color} strokeWidth={cell}/>
      <rect x={(x+2)*cell} y={(y+2)*cell} width={cell*3} height={cell*3} rx={dot==='square'?0:cell} fill={color}/>
    </g>
  );
  return (
    <div className="inline-flex flex-col items-center">
      <div className="bg-white p-2 rounded-lg" style={frame?{border:`2px solid ${frameColor||color}`,borderRadius:12}:{}}>
        <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
          {mods.map(([r,c])=>dot==='dots'
            ? <circle key={r+'-'+c} cx={(c+0.5)*cell} cy={(r+0.5)*cell} r={cell*0.42} fill={color}/>
            : <rect key={r+'-'+c} x={c*cell+(dot==='rounded'?cell*0.08:0)} y={r*cell+(dot==='rounded'?cell*0.08:0)} width={cell*(dot==='rounded'?0.84:1)} height={cell*(dot==='rounded'?0.84:1)} rx={dot==='rounded'?cell*0.3:0} fill={color}/>)}
          {eye(0,0)}{eye(N-7,0)}{eye(0,N-7)}
          {logo && <g><rect x={8*cell} y={8*cell} width={cell*5} height={cell*5} rx={cell} fill="white" stroke={color} strokeWidth="1"/><text x={10.5*cell} y={10.6*cell} textAnchor="middle" dominantBaseline="central" fontSize={cell*2.4} fontWeight="800" fill={color}>B</text></g>}
        </svg>
      </div>
      {frame && <span className="mt-1 text-[9px] font-extrabold uppercase tracking-wide px-2 py-0.5 rounded-full text-white whitespace-nowrap" style={{background:frameColor||color}}>{frame}</span>}
    </div>
  );
}
function PackageInserts() {
  const [title, setTitle] = React.useState('');
  const [sub, setSub] = React.useState('');
  const [bg, setBg] = React.useState('#FFFFFF');
  const [url, setUrl] = React.useState('');
  const [qrColor, setQrColor] = React.useState('#1B2733');
  const [qrDot, setQrDot] = React.useState('square');
  const [qrLogo, setQrLogo] = React.useState(true);
  const [qrFrame, setQrFrame] = React.useState(true);
  const [qrCta, setQrCta] = React.useState('');
  const contrastOk = (h=>{const n=parseInt((h||'#000').slice(1),16);const L=0.2126*(n>>16&255)+0.7152*(n>>8&255)+0.0722*(n&255);return L<160;})(qrColor);
  return (
    <>
      <PageHeader crumbs={['Package Inserts','Generate Package Insert']} title="Generate Package Insert"/>
      <div className="px-7 py-6 grid lg:grid-cols-[1fr_1fr] gap-6 items-start">
        <Card className="p-6 space-y-5">
          <Field label="Campaign" hint="Pick a campaign for the QR code">
            <Select defaultValue=""><option value="" disabled>Select a campaign</option><option>SPAIN</option><option>Australia Campaign</option></Select>
          </Field>
          <div>
            <span className="block text-[13px] font-semibold text-ink mb-2">Upload your brand logo</span>
            <div className="rounded-xl border-2 border-dashed border-brand/40 bg-brand-50/30 py-7 text-center">
              <div className="inline-flex items-center justify-center w-11 h-11 rounded-full bg-white shadow-soft mb-2">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#0096DB" strokeWidth="2">
                  <path d="M7 14a4 4 0 0 1 .5-8A6 6 0 0 1 19 7a4 4 0 0 1-1 8M12 11v9m-4-5l4-4 4 4"/>
                </svg>
              </div>
              <p className="text-[13px] text-ink-muted">
                Drag your file(s) or <a className="text-brand font-semibold cursor-pointer">browse</a>
              </p>
            </div>
          </div>
          <Field label="Title text">
            <Input placeholder="Eg. Claim Your Reward Now!" value={title} onChange={e=>setTitle(e.target.value)}/>
          </Field>
          <Field label="Background color">
            <div className="flex items-center gap-2">
              <Input value={bg} onChange={e=>setBg(e.target.value)} placeholder="#ffffff"/>
              <input type="color" value={bg} onChange={e=>setBg(e.target.value)}
                className="w-12 h-11 rounded-lg border border-gray-200 cursor-pointer"/>
            </div>
          </Field>
          <Field label="Sub-title text">
            <textarea value={sub} onChange={e=>setSub(e.target.value)}
              rows={3} placeholder="Eg. Scan this QR code to redeem your rebate."
              className="w-full bg-surface-input rounded-lg px-4 py-3 text-[14px] text-ink placeholder:text-slate-400 outline-none focus:ring-2 focus:ring-brand-200 resize-none"/>
          </Field>
          <Field label="Your website or social media link">
            <Input placeholder="Eg. www.yoursite.com" value={url} onChange={e=>setUrl(e.target.value)}/>
          </Field>
          <div className="rounded-xl border border-line bg-surface-subtle/60 p-4 space-y-3">
            <div className="flex items-center justify-between gap-3">
              <span className="text-[13px] font-bold text-ink">Branded QR code</span>
              <span className="text-[11px] font-bold px-2.5 py-1 rounded-full acc-bg-soft acc-text">New</span>
            </div>
            <Field label="QR color">
              <div className="flex items-center gap-2">
                <Input value={qrColor} onChange={e=>setQrColor(e.target.value)} placeholder="#1B2733"/>
                <input type="color" value={qrColor} onChange={e=>setQrColor(e.target.value)} className="w-12 h-11 rounded-lg border border-gray-200 cursor-pointer"/>
              </div>
            </Field>
            {!contrastOk && <p className="text-[11px] text-rose-500 font-semibold">This color is too light — scanners may fail. Pick a darker shade.</p>}
            <div>
              <span className="block text-[12px] font-semibold text-ink mb-1.5">Dot style</span>
              <div className="flex gap-2">
                {[['square','Classic'],['rounded','Rounded'],['dots','Dots']].map(([id,lb])=>(
                  <button type="button" key={id} onClick={()=>setQrDot(id)}
                    className={"px-3 py-2 rounded-lg text-[12px] font-bold border transition-colors "+(qrDot===id?"bg-brand text-white border-brand":"bg-white text-ink-muted border-line hover:border-brand-200")}>{lb}</button>
                ))}
              </div>
            </div>
            <div className="flex items-center justify-between gap-3 bg-white border border-line rounded-lg px-3 py-2.5">
              <span className="text-[12px] font-semibold text-ink">Logo in center <span className="font-normal text-ink-muted">— uses your brand logo</span></span>
              <StatusToggle checked={qrLogo} onChange={()=>setQrLogo(v=>!v)}/>
            </div>
            <div className="flex items-center justify-between gap-3 bg-white border border-line rounded-lg px-3 py-2.5">
              <span className="text-[12px] font-semibold text-ink">Frame with call-to-action</span>
              <StatusToggle checked={qrFrame} onChange={()=>setQrFrame(v=>!v)}/>
            </div>
            {qrFrame && (
              <Field label="Frame text">
                <Input placeholder="Eg. Scan to claim your reward" value={qrCta} onChange={e=>setQrCta(e.target.value)}/>
              </Field>
            )}
          </div>
          <BtnPrimary>Download</BtnPrimary>
        </Card>

        {/* Preview */}
        <div className="lg:sticky lg:top-6 flex flex-col items-center">
          <span className="px-3 py-1 text-[11px] font-semibold rounded-full bg-brand-50 text-brand mb-4">Preview of your Package Insert</span>
          <div className="bg-white rounded-xl shadow-soft border border-gray-100 overflow-hidden w-full max-w-md">
            <div className="grid grid-cols-[1fr_auto] gap-4 p-6" style={{background:bg || '#ffffff'}}>
              <div>
                <div className="w-12 h-12 rounded-full bg-gray-200 mb-3 inline-flex items-center justify-center text-[10px] text-ink-muted font-semibold">LOGO</div>
                <h3 className="text-[16px] font-bold text-ink leading-tight">
                  {title || 'Your title text here..'}
                </h3>
                <p className="text-[11px] text-ink-muted leading-snug mt-2 max-w-[200px]">
                  {sub || 'Your subtitle text goes here. Use this space to provide additional details or instructions for users about the offer or promotion linked to the QR code.'}
                </p>
              </div>
              <div className="flex flex-col items-center justify-between border-l border-dashed border-gray-300 pl-4">
                <BrandedQR size={96} color={qrColor} dot={qrDot} logo={qrLogo} frame={qrFrame ? (qrCta || 'Scan to claim') : null}/>
                <span className="text-[10px] text-ink-muted mt-2">{url || 'www.yourwebsite.com'}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { AddProduct, CreatePromotion, AddCampaign, PackageInserts, BrandedQR });


/* ─── Seller Panel — Settings (4 sub-tabs) ─────────────────────────────────── */

const SETTINGS_TABS = [
  { id:'account',  label:'Account settings' },
  { id:'brand',    label:'Brand Details' },
  { id:'billing',  label:'Plans & Billing' },
  { id:'password', label:'Change Password' },
];

function Settings({ subRoute, onSubNav }) {
  const tab = SETTINGS_TABS.find(t => t.id === subRoute) ? subRoute : 'account';
  return (
    <>
      <PageHeader title="Settings"/>
      <div className="px-7 py-6 grid lg:grid-cols-[220px_1fr] gap-6 items-start">
        <Card className="p-2">
          {SETTINGS_TABS.map(t => {
            const isActive = tab === t.id;
            return (
              <button key={t.id} onClick={() => onSubNav(t.id)}
                className={
                  "w-full text-left px-4 py-3 rounded-lg text-[13.5px] font-medium transition-colors flex items-center justify-between " +
                  (isActive ? "bg-brand-50 text-brand border-l-4 border-brand" : "text-ink-muted hover:bg-gray-50")
                }>
                {t.label}
              </button>
            );
          })}
        </Card>

        <Card className="p-6 min-h-[420px]">
          {tab === 'account'  && <SettingsAccount/>}
          {tab === 'brand'    && <SettingsBrand/>}
          {tab === 'billing'  && <SettingsBilling/>}
          {tab === 'password' && <SettingsPassword/>}
        </Card>
      </div>
    </>
  );
}

/* ── Account tab ───────────────────────────────────────────────────────────── */
function SettingsAccount() {
  return (
    <div>
      <div className="flex items-center justify-between mb-5">
        <h3 className="text-[16px] font-bold text-ink">Profile</h3>
        <BtnGhost>
          <svg width="14" height="14" 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>
          Edit
        </BtnGhost>
      </div>

      <div className="flex items-center gap-4 mb-6">
        <div className="w-16 h-16 rounded-full text-white font-bold text-2xl flex items-center justify-center"
             style={{backgroundImage:'linear-gradient(135deg, var(--accent), var(--accent-dark))'}}>
          D
        </div>
      </div>

      <h4 className="text-[13.5px] font-bold text-ink mb-4">Personal Info & Contact details</h4>
      <div className="grid md:grid-cols-2 gap-4 max-w-3xl">
        <Field label="First Name"><Input defaultValue="Demo" readOnly/></Field>
        <Field label="Last Name"><Input defaultValue="User" readOnly/></Field>
        <div className="md:col-span-2">
          <Field label="Phone Number">
            <div className="flex items-center gap-2">
              <span className="bg-surface-input rounded-lg px-3 py-3 text-[14px] flex items-center gap-1">🇺🇸 <span className="text-ink-muted">+1</span></span>
              <Input defaultValue="555 010 1234" readOnly/>
            </div>
          </Field>
        </div>
        <div className="md:col-span-2">
          <Field label="Email"><Input defaultValue="demo.user@reviewbuddie.com" readOnly/></Field>
        </div>
      </div>

      <h4 className="text-[13.5px] font-bold text-ink mt-7 mb-3">Brand Details</h4>
      <div className="border border-brand/30 rounded-lg p-4 max-w-3xl flex items-center gap-3">
        <span className="w-7 h-7 rounded bg-brand/10 text-brand font-bold text-[11px] flex items-center justify-center">B</span>
        <span className="text-[14px] font-semibold text-ink">Brontix</span>
      </div>
    </div>
  );
}

/* ── Brand Details tab (list + add form) ───────────────────────────────────── */
function SettingsBrand() {
  const [mode, setMode] = React.useState('list');   // 'list' | 'add'
  if (mode === 'add') return <AddBrandForm onCancel={() => setMode('list')} onSave={() => setMode('list')}/>;
  return (
    <div>
      <h3 className="text-[16px] font-bold text-ink mb-5">Brands</h3>
      <div className="flex items-center justify-between mb-4">
        <span className="text-[14px] font-semibold text-ink">Brand Details</span>
        <a onClick={() => setMode('add')} className="text-brand font-semibold text-[13.5px] cursor-pointer hover:text-brand-dark">
          Add New Brand
        </a>
      </div>
      <div className="border border-brand/30 rounded-lg p-4 flex items-center justify-between">
        <div className="flex items-center gap-3">
          <span className="w-7 h-7 rounded bg-brand/10 text-brand font-bold text-[11px] flex items-center justify-center">B</span>
          <span className="text-[14px] font-semibold text-ink">Brontix</span>
        </div>
        <div className="flex items-center gap-2">
          <button className="w-8 h-8 rounded-full text-ink-muted hover:bg-gray-100 flex items-center justify-center">
            <svg width="14" height="14" 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 className="w-8 h-8 rounded-full text-rose-500 hover:bg-rose-50 flex items-center justify-center">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><circle cx="12" cy="12" r="9"/><path d="M9 9l6 6M15 9l-6 6"/></svg>
          </button>
        </div>
      </div>
    </div>
  );
}

function AddBrandForm({ onCancel, onSave }) {
  const [brandName, setBrandName] = React.useState('');
  const social = [
    { k:'instagram', color:'bg-gradient-to-br from-rose-500 via-amber-500 to-yellow-500', icon:'M' },
    { k:'facebook',  color:'bg-blue-600',  icon:'f' },
    { k:'linkedin',  color:'bg-blue-700',  icon:'in' },
    { k:'youtube',   color:'bg-red-600',   icon:'▶' },
  ];
  return (
    <div>
      <div className="flex items-center gap-2 mb-5">
        <h3 className="text-[16px] font-bold text-ink">Brands</h3>
      </div>
      <h4 className="text-[14px] font-semibold text-ink mb-4">Brand Details</h4>
      <div className="space-y-5 max-w-4xl">
        <Field label="Your Brand Name" required>
          <Input value={brandName} onChange={e=>setBrandName(e.target.value)} placeholder="Enter brand name"/>
        </Field>
        <div>
          <span className="block text-[13px] font-semibold text-ink mb-2">Upload your brand logo</span>
          <div className="rounded-xl border-2 border-dashed border-brand/40 bg-brand-50/30 py-8 text-center">
            <div className="inline-flex items-center justify-center w-11 h-11 rounded-full bg-white shadow-soft mb-2">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#0096DB" strokeWidth="2">
                <path d="M7 14a4 4 0 0 1 .5-8A6 6 0 0 1 19 7a4 4 0 0 1-1 8M12 11v9m-4-5l4-4 4 4"/>
              </svg>
            </div>
            <p className="text-[13px] text-ink-muted">
              Drag your file(s) or <a className="text-brand font-semibold cursor-pointer">browse</a>
            </p>
          </div>
        </div>
        <div className="grid sm:grid-cols-2 gap-4">
          {social.map(s => (
            <Field key={s.k} label={
              <span className="inline-flex items-center gap-2">
                <span className={"w-5 h-5 rounded text-white text-[11px] font-bold inline-flex items-center justify-center " + s.color}>{s.icon}</span>
                <span className="capitalize">{s.k}</span>
              </span>
            }>
              <Input placeholder="Enter the url"/>
            </Field>
          ))}
        </div>
        <div className="flex items-center gap-3 pt-2">
          <BtnGhost onClick={onCancel}>Cancel</BtnGhost>
          <BtnPrimary disabled={!brandName.trim()} onClick={onSave}>Add Brand</BtnPrimary>
        </div>
      </div>
    </div>
  );
}

/* ── Plans & Billing tab ───────────────────────────────────────────────────── */
function SettingsBilling() {
  return (
    <div>
      <h3 className="text-[16px] font-bold text-ink mb-5">Plans & Billing</h3>
      <h4 className="text-[14px] font-semibold text-ink mb-3">Current Plan</h4>
      <div className="rounded-lg border border-gray-200 p-5 flex items-center justify-between gap-4 flex-wrap mb-7">
        <div>
          <div className="text-[15px] font-bold text-ink">FREE Plan – Risk Free</div>
          <ul className="mt-2 space-y-1 text-[12.5px] text-ink-muted">
            <li className="inline-flex items-center gap-1.5">✓ Upto 30 Reviews</li>
            <li className="inline-flex items-center gap-1.5 ml-4">✓ Upto 30 Leads & Marketplace Redirections</li>
          </ul>
          <p className="text-[11px] text-slate-400 mt-2">billed</p>
        </div>
        <BtnGhost onClick={()=>window.__openPricing && window.__openPricing()}>Upgrade plan</BtnGhost>
      </div>

      <div className="flex items-center justify-between mb-3">
        <h4 className="text-[14px] font-semibold text-ink">Transaction History</h4>
        <a className="text-brand font-semibold text-[13px] cursor-pointer">Download CSV</a>
      </div>
      <Card>
        <table className="w-full text-[13.5px]">
          <thead>
            <tr className="bg-surface-subtle text-[11.5px] uppercase tracking-wider text-ink-muted">
              <th className="text-left font-semibold px-5 py-3.5">Date</th>
              <th className="text-left font-semibold px-3 py-3.5">Order ID</th>
              <th className="text-left font-semibold px-3 py-3.5">Plan</th>
              <th className="text-right font-semibold px-5 py-3.5">Amount</th>
            </tr>
          </thead>
          <tbody>
            <tr><td colSpan="4" className="text-center py-10 text-ink-muted">No Transactions found</td></tr>
          </tbody>
        </table>
      </Card>
    </div>
  );
}

/* ── Change Password tab ───────────────────────────────────────────────────── */
function SettingsPassword() {
  const [oldShow, setOldShow] = React.useState(false);
  const [newShow, setNewShow] = React.useState(false);
  return (
    <div>
      <h3 className="text-[16px] font-bold text-ink mb-1">Password and Security</h3>
      <p className="text-[12.5px] text-ink-muted mb-5">Update your password</p>
      <div className="space-y-4 max-w-md">
        <PasswordField label="Old password" show={oldShow} onToggle={() => setOldShow(v => !v)} placeholder="Enter your old password here"/>
        <PasswordField label="New password" show={newShow} onToggle={() => setNewShow(v => !v)} placeholder="Enter new password here"/>
      </div>
      <div className="mt-6">
        <BtnPrimary>Update</BtnPrimary>
      </div>
    </div>
  );
}
function PasswordField({ label, show, onToggle, placeholder }) {
  return (
    <Field label={label}>
      <div className="relative">
        <input type={show ? 'text' : 'password'} placeholder={placeholder}
          className="w-full bg-surface-input rounded-lg px-4 py-3 pr-11 text-[14px] text-ink placeholder:text-slate-400 outline-none focus:ring-2 focus:ring-brand-200"/>
        <button onClick={onToggle} className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-ink">
          {show ? (
            <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12z"/><circle cx="12" cy="12" r="3"/></svg>
          ) : (
            <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M17.94 17.94A10 10 0 0 1 12 20c-7 0-11-8-11-8a18.5 18.5 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.4 18.4 0 0 1-2.16 3.19M14.12 14.12a3 3 0 1 1-4.24-4.24M1 1l22 22"/></svg>
          )}
        </button>
      </div>
    </Field>
  );
}

Object.assign(window, { Settings });


/* ─── Seller Panel — App router ────────────────────────────────────────────── */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": ["#0096DB", "#0077B8", "#E8F6FD", "rgba(0,150,219,.28)"],
  "sidebar": "Navy",
  "typeface": "Plus Jakarta Sans",
  "promoLayout": "Standard",
  "cardStyle": "Image well",
  "campLayout": "List rows",
  "promoListLayout": "List rows",
  "animSet": "Classic"
}/*EDITMODE-END*/;

const ACCENTS = {
  Blue:    ["#0096DB", "#0077B8", "#E8F6FD", "rgba(0,150,219,.28)"],
  Violet:  ["#6C57E0", "#5340C4", "#F2EFFD", "rgba(108,87,224,.28)"],
  Emerald: ["#0FA968", "#0B8451", "#E8F8F0", "rgba(15,169,104,.26)"],
  Coral:   ["#F2683C", "#D44E26", "#FDEEE8", "rgba(242,104,60,.26)"],
};
const SIDEBARS = { Navy:"#0E1A24", Charcoal:"#171A1F", Ink:"#10131A" };

function SellerApp() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // apply theme tweaks to CSS variables + body font
  React.useEffect(() => {
    const a = Array.isArray(t.accent) ? t.accent : ACCENTS.Violet;
    const r = document.documentElement.style;
    r.setProperty('--accent', a[0]);
    r.setProperty('--accent-dark', a[1]);
    r.setProperty('--accent-50', a[2]);
    r.setProperty('--accent-ring', a[3]);
    r.setProperty('--sidebar-bg', SIDEBARS[t.sidebar] || '#0E1A24');
    document.body.style.fontFamily = `'${t.typeface || 'Plus Jakarta Sans'}','Inter',system-ui,sans-serif`;
    window.__pricingHelper = t.planHelper !== false;
    window.__animSet = t.animSet || 'All';
    window.__pcV2 = { badge:t.pcBadge===true, expiry:t.pcExpiry===true, socials:t.pcSocials===true, cta:t.pcCta!==false, pillGrid:t.pcPillGrid===true, blobs:t.pcBlobs!==false, steps:t.pcSteps===true };
  }, [t.accent, t.sidebar, t.typeface, t.planHelper, t.animSet, t.pcBadge, t.pcExpiry, t.pcSocials, t.pcCta, t.pcPillGrid, t.pcBlobs, t.pcSteps]);

  const [route, setRoute]       = React.useState(window.__initialRoute || 'dashboard');
  const [ctx, setCtx]           = React.useState(null);          // misc payload for sub-screens
  const [settingsTab, setStab]  = React.useState('account');

  // navigation helper exposed to every screen
  const onNav = (next, payload) => {
    setCtx(payload || null);
    if (next.startsWith?.('settings:')) {
      setStab(next.split(':')[1] || 'account');
      setRoute('settings');
    } else {
      setRoute(next);
    }
    if (typeof window !== 'undefined') window.scrollTo({ top:0, behavior:'instant' });
  };

  // map an internal route → which sidebar item to highlight
  const activeSidebar = (() => {
    if (route === 'product-add') return 'products';
    if (route === 'promotion-create') return 'promotions';
    if (route === 'campaign-add') return 'campaigns';
    return route;
  })();

  // screen switcher
  const Screen = (() => {
    switch (route) {
      case 'dashboard':         return <Dashboard onNav={onNav} newSeller={t.dashState === 'New seller'}/>;
      case 'analytics':         return window.AnalyticsPage ? <AnalyticsPage/> : <Dashboard onNav={onNav}/>;
      case 'products':          return <Products  onNav={onNav} cardStyle={t.cardStyle || 'Image well'}/>;
      case 'product-add':       return <AddProduct onNav={onNav}/>;
      case 'promotions':        return <Promotions onNav={onNav} layout={t.promoListLayout || 'List rows'}/>;
      case 'promotion-create':  return (t.promoLayout === 'Studio' && window.CreatePromotionStudio)
                                        ? <CreatePromotionStudio ctx={ctx}/>
                                        : <CreatePromotion ctx={ctx} layout={t.promoLayout || 'Standard'}/>;
      case 'campaigns':         return <Campaigns onNav={onNav} layout={t.campLayout || 'List rows'}/>;
      case 'claims':            return window.ClaimCenter ? <ClaimCenter onNav={onNav}/> : <Dashboard onNav={onNav}/>;
      case 'campaign-add':      return <AddCampaign/>;
      case 'inserts':           return <PackageInserts/>;
      case 'customers':         return <Customers/>;
      case 'referrals':         return window.ReferEarn ? <ReferEarn onNav={onNav}/> : <Dashboard onNav={onNav}/>;
      case 'knowledge':         return window.KnowledgeCenter ? <KnowledgeCenter/> : <Dashboard onNav={onNav}/>;
      case 'settings':          return <Settings subRoute={settingsTab} onSubNav={setStab}/>;
      default:                  return <Dashboard onNav={onNav} newSeller={t.dashState === 'New seller'}/>;
    }
  })();

  return (
    <>
      {(t.device === 'Mobile' && window.MobileApp)
        ? <MobileApp/>
        : <AppShell active={activeSidebar} onNav={onNav}>
            {Screen}
          </AppShell>}
      <TweaksPanel>
        {window.MobileApp && <>
          <TweakSection label="Device"/>
          <TweakRadio label="Preview as" value={t.device || 'Desktop'}
            options={['Desktop','Mobile']}
            onChange={(v) => setTweak('device', v)}/>
        </>}
        <TweakSection label="Accent"/>
        <TweakColor label="Accent color" value={t.accent}
          options={Object.values(ACCENTS)}
          onChange={(v) => setTweak('accent', v)}/>
        <TweakSection label="Sidebar"/>
        <TweakRadio label="Shade" value={t.sidebar}
          options={Object.keys(SIDEBARS)}
          onChange={(v) => setTweak('sidebar', v)}/>
        <TweakSection label="Typography"/>
        <TweakSelect label="Typeface" value={t.typeface}
          options={['Plus Jakarta Sans','Inter','Manrope','Sora']}
          onChange={(v) => setTweak('typeface', v)}/>
        <TweakSection label="Promotion create page"/>
        <TweakRadio label="Layout" value={t.promoLayout || 'Standard'}
          options={window.CreatePromotionStudio ? ['Standard','Clean','Studio'] : ['Standard','Clean']}
          onChange={(v) => setTweak('promoLayout', v)}/>
        {window.Dashboard?.v2 && <>
          <TweakSection label="Dashboard"/>
          <TweakRadio label="State" value={t.dashState || 'With data'}
            options={['With data','New seller']}
            onChange={(v) => setTweak('dashState', v)}/>
        </>}
        {window.__pcV2Ready && <>
          <TweakSection label="Promo card"/>
          <TweakToggle label="Value badge" value={t.pcBadge===true} onChange={(v)=>setTweak('pcBadge',v)}/>
          <TweakToggle label="Expiry line" value={t.pcExpiry===true} onChange={(v)=>setTweak('pcExpiry',v)}/>
          <TweakToggle label="Social footer" value={t.pcSocials===true} onChange={(v)=>setTweak('pcSocials',v)}/>
          <TweakToggle label="CTA shine + hover" value={t.pcCta!==false} onChange={(v)=>setTweak('pcCta',v)}/>
          <TweakToggle label="Pill grid (3-up)" value={t.pcPillGrid===true} onChange={(v)=>setTweak('pcPillGrid',v)}/>
          <TweakToggle label="Gradient blobs" value={t.pcBlobs!==false} onChange={(v)=>setTweak('pcBlobs',v)}/>
          <TweakToggle label="Step indicator" value={t.pcSteps===true} onChange={(v)=>setTweak('pcSteps',v)}/>
        </>}
        {window.__promoAnimsV2 && <>
          <TweakSection label="Promo animations"/>
          <TweakRadio label="Animation set" value={t.animSet || 'All'}
            options={['All','New','Classic']}
            onChange={(v) => setTweak('animSet', v)}/>
        </>}
        {window.PricingModalHost && <>
          <TweakSection label="Pricing modal"/>
          <TweakToggle label="Plan-fit slider" value={t.planHelper !== false}
            onChange={(v) => setTweak('planHelper', v)}/>
        </>}
        {window.Products?.v2 && <>
          <TweakSection label="Products page"/>
          <TweakRadio label="Card style" value={t.cardStyle || 'Image well'}
            options={['Image well','Side thumb','Square tile']}
            onChange={(v) => setTweak('cardStyle', v)}/>
        </>}
        {window.Promotions?.v2 && <>
          <TweakSection label="Promotions page"/>
          <TweakRadio label="Layout" value={t.promoListLayout || 'List rows'}
            options={['List rows','Cards']}
            onChange={(v) => setTweak('promoListLayout', v)}/>
        </>}
        {window.Campaigns?.v2 && <>
          <TweakSection label="Campaigns page"/>
          <TweakRadio label="Layout" value={t.campLayout || 'List rows'}
            options={['List rows','Compact table','Cards']}
            onChange={(v) => setTweak('campLayout', v)}/>
        </>}
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<SellerApp/>);
