/* shared brand list — Settings edits it, Create Promotion reads it */
window.RB_BRANDS = window.RB_BRANDS || [
  { name:'Brontix', logo:null, socials:{ instagram:'instagram.com/brontix', website:'brontix.com' } },
];

/* ─── Settings page — v2 redesign ────────────────────────────────────────────
   Icon rail + per-tab cards. Brand Details: brands as cards with logo,
   socials, and an edit form (logo + social links optional).
   Loads AFTER extras.jsx and overrides window.Settings. */

const SET_TABS_V2 = [
  { id:'account',  label:'Account',         d:'Profile & contact info',
    icon:<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></svg> },
  { id:'brand',    label:'Brand Details',   d:'Logos & social links',
    icon:<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 2l7 4v6c0 5-3.5 8.5-7 10-3.5-1.5-7-5-7-10V6z"/></svg> },
  { id:'billing',  label:'Plans & Billing', d:'Subscription & invoices',
    icon:<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="2" y="5" width="20" height="14" rx="2"/><path d="M2 10h20"/></svg> },
  { id:'password', label:'Password',        d:'Security settings',
    icon:<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="4" y="11" width="16" height="9" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg> },
  { id:'payouts',  label:'Affiliate Payouts', d:'Wallet & withdrawals',
    icon:<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 12V7H5a2 2 0 0 1 0-4h14v4"/><path d="M3 5v14a2 2 0 0 0 2 2h16v-5"/><path d="M18 12a2 2 0 0 0 0 4h4v-4z"/></svg> },
];

const SOCIALS_V2 = [
  { k:'instagram', label:'Instagram', color:'bg-gradient-to-br from-rose-500 via-amber-500 to-yellow-500', icon:'Ig' },
  { k:'facebook',  label:'Facebook',  color:'bg-blue-600',  icon:'f' },
  { k:'linkedin',  label:'LinkedIn',  color:'bg-blue-700',  icon:'in' },
  { k:'youtube',   label:'YouTube',   color:'bg-red-600',   icon:'▶' },
  { k:'x',         label:'X (Twitter)', color:'bg-ink',     icon:'𝕏' },
  { k:'website',   label:'Website',   color:'bg-brand',     icon:'🌐' },
];


function BrandLogoWell({ brand, size = 'h-24' }) {
  return (
    <div className={"rounded-xl bg-surface-subtle border border-line/70 flex items-center justify-center "+size}>
      {brand.logo
        ? <img src={brand.logo} alt={brand.name} className="max-h-[70%] max-w-[70%] object-contain"/>
        : <span className="w-12 h-12 rounded-xl acc-bg-soft acc-text font-extrabold text-[18px] flex items-center justify-center">{(brand.name||'?')[0]}</span>}
    </div>
  );
}

function BrandFormV2({ brand, onCancel, onSave }) {
  const [name, setName]       = React.useState(brand?.name || '');
  const [logo, setLogo]       = React.useState(brand?.logo || null);
  const [socials, setSocials] = React.useState(brand?.socials || {});
  const [biz, setBiz]         = React.useState(brand?.business || { type:'product', category:'', gbp:'', address:'', phone:'', email:'' });
  const setB = (k,v) => setBiz(x => ({...x, [k]:v}));
  const loadLogo = f => { if(!f || !f.type.startsWith('image/')) return; const r=new FileReader(); r.onload=()=>setLogo(r.result); r.readAsDataURL(f); };
  const setSoc = (k,v) => setSocials(s => ({...s, [k]:v}));
  return (
    <Card className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <h3 className="text-[16px] font-bold text-ink">{brand ? 'Edit brand' : 'Add new brand'}</h3>
        <div className="flex gap-2">
          <BtnGhost onClick={onCancel}>Cancel</BtnGhost>
          <BtnPrimary disabled={!name.trim()} onClick={()=>onSave({ name:name.trim(), logo, socials, business:biz })}>{brand ? 'Save changes' : 'Add Brand'}</BtnPrimary>
        </div>
      </div>
      <div className="max-w-2xl space-y-6">
        <Field label="Brand name" required hint="Shown to customers on the claim page">
          <Input value={name} onChange={e=>setName(e.target.value)} placeholder="Enter brand name"/>
        </Field>
        <div>
          <span className="block text-[13px] font-bold text-ink mb-1.5">Business type</span>
          <div className="inline-flex bg-surface-input rounded-xl p-1 gap-1">
            {[['product','Product'],['service','Service'],['both','Both']].map(([v,l]) => (
              <button key={v} onClick={()=>setB('type',v)} className={"px-4 py-2 rounded-lg text-[13px] font-bold transition-colors "+(biz.type===v ? 'bg-white text-ink shadow-soft' : 'text-ink-muted hover:text-ink')}>{l}</button>
            ))}
          </div>
        </div>
        {biz.type !== 'product' && (
          <div className="rounded-2xl border border-line bg-surface-subtle/50 p-5 space-y-5">
            <div>
              <span className="text-[13px] font-bold text-ink">Service details</span>
              <p className="text-[12px] text-ink-muted mt-0.5">Helps customers find and contact you after leaving a review.</p>
            </div>
            <div className="grid sm:grid-cols-2 gap-4">
              <Field label="Google Business Profile" hint="Customers can be routed here to leave a Google review">
                <Input value={biz.gbp} onChange={e=>setB('gbp', e.target.value)} placeholder="g.page/your-business"/>
              </Field>
            </div>
            <Field label="Business address" hint="Shown on your claim page so local customers can find you">
              <Input value={biz.address} onChange={e=>setB('address', e.target.value)} placeholder="Shop 4, Linking Road, Bandra West, Mumbai 400050"/>
            </Field>
          </div>
        )}
        <div>
          <span className="block text-[13px] font-bold text-ink mb-1.5">Contact details <span className="text-[11px] font-normal text-ink-muted ml-1">shown to customers who need help with a claim</span></span>
          <div className="grid sm:grid-cols-2 gap-4">
            <Input value={biz.phone} onChange={e=>setB('phone', e.target.value)} placeholder="Contact phone · +91 98765 43210"/>
            <Input value={biz.email} onChange={e=>setB('email', e.target.value)} placeholder="Contact email · hello@yourbrand.com"/>
          </div>
        </div>
        <div>
          <span className="block text-[13px] font-bold text-ink mb-1.5">Brand logo <span className="text-[11px] font-normal text-ink-muted ml-1">optional</span></span>
          {logo ? (
            <div className="flex items-center gap-4">
              <img src={logo} alt="Logo" className="w-20 h-20 rounded-xl object-contain bg-surface-subtle border border-line p-2"/>
              <div className="space-y-1">
                <label className="block text-[12.5px] font-bold acc-text cursor-pointer hover:opacity-80">
                  Replace logo
                  <input type="file" accept="image/*" className="hidden" onChange={e=>loadLogo(e.target.files[0])}/>
                </label>
                <button onClick={()=>setLogo(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(); loadLogo(e.dataTransfer.files[0]);}}
              className="block border-2 border-dashed border-gray-200 hover:border-[var(--accent)] rounded-2xl py-7 text-center cursor-pointer transition-colors">
              <input type="file" accept="image/*" className="hidden" onChange={e=>loadLogo(e.target.files[0])}/>
              <svg className="mx-auto text-ink-soft" width="24" height="24" 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 logo here or <span className="acc-text">browse</span></p>
              <p className="text-[11px] text-ink-soft mt-1">PNG or SVG with transparent background works best</p>
            </label>
          )}
        </div>
        <div>
          <div className="flex items-center gap-2 mb-1.5">
            <span className="text-[13px] font-bold text-ink">Social media links</span>
            <span className="text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-full bg-surface-input text-ink-muted">Optional</span>
          </div>
          <p className="text-[12px] text-ink-muted mb-3">Shown as follow buttons after a customer leaves a review.</p>
          <div className="grid sm:grid-cols-2 gap-3">
            {SOCIALS_V2.map(s => (
              <div key={s.k} className="relative">
                <span className={"absolute left-2.5 top-1/2 -translate-y-1/2 w-6 h-6 rounded-md text-white text-[10px] font-bold flex items-center justify-center "+s.color}>{s.icon}</span>
                <input value={socials[s.k]||''} onChange={e=>setSoc(s.k, e.target.value)} placeholder={s.label+' URL'}
                  className="w-full bg-surface-input border border-transparent rounded-xl pl-11 pr-4 py-3 text-[13.5px] text-ink placeholder:text-ink-soft outline-none focus:bg-white focus:border-brand-200 acc-ring transition"/>
              </div>
            ))}
          </div>
        </div>
      </div>
    </Card>
  );
}

function SettingsBrandV2() {
  const [brands, setBrands] = React.useState(window.RB_BRANDS);
  const syncBrands = (next) => { window.RB_BRANDS = next; setBrands(next); };
  const [editing, setEditing] = React.useState(null);   // null | index | 'new'
  if (editing !== null) {
    const isNew = editing === 'new';
    return <BrandFormV2 brand={isNew ? null : brands[editing]}
      onCancel={()=>setEditing(null)}
      onSave={(b)=>{ syncBrands(isNew ? [...brands, b] : brands.map((x,i)=>i===editing?b:x)); setEditing(null); }}/>;
  }
  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-[16px] font-bold text-ink flex items-center gap-2">Brands <InfoTip text="The brands shown on your claim pages and package inserts — add logos, business details and social links."/></h3>
          <p className="text-[12.5px] text-ink-muted mt-0.5">Your brands appear on claim pages and package inserts.</p>
        </div>
      </div>
      <div className="grid gap-4" style={{gridTemplateColumns:'repeat(auto-fill, minmax(240px, 1fr))'}}>
        {brands.map((b,i) => {
          const links = SOCIALS_V2.filter(s => (b.socials||{})[s.k]);
          return (
            <div key={i} className="bg-white rounded-2xl border border-line shadow-soft hover:shadow-card hover:border-brand-200 transition-all p-4 flex flex-col gap-3">
              <BrandLogoWell brand={b}/>
              <div>
                <p className="font-bold text-[14px] text-ink">{b.name}</p>
                {b.business && b.business.type !== 'product' && (
                  <p className="text-[11.5px] text-ink-muted mt-0.5">{[b.business.address && b.business.address.split(',').slice(-2)[0]?.trim() || 'Service'].filter(Boolean).join(' · ')}</p>
                )}
              </div>
              <div className="flex items-center gap-1.5 min-h-[24px]">
                {links.length
                  ? links.map(s => <span key={s.k} title={s.label} className={"w-6 h-6 rounded-md text-white text-[10px] font-bold flex items-center justify-center "+s.color}>{s.icon}</span>)
                  : <span className="text-[11.5px] text-ink-soft">No social links yet</span>}
              </div>
              <div className="mt-auto pt-3 border-t border-line/70 flex items-center justify-between">
                <button onClick={()=>setEditing(i)} className="text-[12.5px] font-bold acc-text hover:opacity-80">Edit brand</button>
                <button className="w-8 h-8 rounded-lg text-ink-soft hover:bg-rose-50 hover:text-rose-600 flex items-center justify-center transition-colors">
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/></svg>
                </button>
              </div>
            </div>
          );
        })}
        <button onClick={()=>setEditing('new')}
          className="min-h-[210px] rounded-2xl border-2 border-dashed border-gray-200 hover:border-[var(--accent)] text-ink-muted hover:acc-text flex flex-col items-center justify-center gap-2 transition-colors">
          <span className="w-10 h-10 rounded-full bg-surface-input flex items-center justify-center">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M12 5v14M5 12h14" strokeLinecap="round"/></svg>
          </span>
          <span className="text-[13px] font-bold">Add new brand</span>
        </button>
      </div>
    </div>
  );
}

/* ── Account tab (production) ─────────────────────────────────────────── */
function SavedFlash({ show }) {
  return show ? <span className="inline-flex items-center gap-1.5 text-[12px] font-bold text-green-600"><svg width="13" height="13" 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>Saved</span> : null;
}

function SettingsAccountV2() {
  const initial = { first:'Demo', last:'User', email:'demo.user@reviewbuddie.com', cc:'+1', phone:'555 010 1234' };
  const [f, setF]           = React.useState(initial);
  const [base, setBase]     = React.useState(initial);
  const [avatar, setAvatar] = React.useState(null);
  const [saved, setSaved]   = React.useState(false);
  const [confirmDel, setConfirmDel] = React.useState(false);
  const set = (k,v) => setF(p=>({...p,[k]:v}));
  const dirty = JSON.stringify(f) !== JSON.stringify(base);
  const emailOk = /^\S+@\S+\.\S+$/.test(f.email);
  const canSave = dirty && emailOk && f.first.trim();
  const save = () => { setBase(f); setSaved(true); setTimeout(()=>setSaved(false), 2200); };
  const loadAvatar = file => { if(!file || !file.type.startsWith('image/')) return; const r=new FileReader(); r.onload=()=>setAvatar(r.result); r.readAsDataURL(file); };
  return (
    <div className="space-y-8">
      <div className="flex items-center justify-between gap-3">
        <div>
          <h3 className="text-[16px] font-bold text-ink">Profile</h3>
          <p className="text-[12.5px] text-ink-muted mt-0.5">Demo account — sample contact details for preview.</p>
        </div>
        <div className="flex items-center gap-3">
          <SavedFlash show={saved}/>
          <BtnPrimary disabled={!canSave} onClick={save}>Save changes</BtnPrimary>
        </div>
      </div>
      <div className="flex items-center gap-5">
        {avatar
          ? <img src={avatar} alt="Profile" className="w-16 h-16 rounded-full object-cover border border-line"/>
          : <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))'}}>{(f.first[0]||'?').toUpperCase()}</div>}
        <div className="space-y-1">
          <label className="block text-[12.5px] font-bold acc-text cursor-pointer hover:opacity-80">
            {avatar ? 'Replace photo' : 'Upload photo'}
            <input type="file" accept="image/*" className="hidden" onChange={e=>loadAvatar(e.target.files[0])}/>
          </label>
          {avatar && <button onClick={()=>setAvatar(null)} className="text-[12.5px] font-bold text-rose-600 hover:text-rose-700">Remove</button>}
          {!avatar && <p className="text-[11px] text-ink-soft">PNG or JPG, square works best</p>}
        </div>
      </div>
      <div className="grid md:grid-cols-2 gap-4 max-w-3xl">
        <Field label="First name" required><Input value={f.first} onChange={e=>set('first',e.target.value)}/></Field>
        <Field label="Last name"><Input value={f.last} onChange={e=>set('last',e.target.value)}/></Field>
        <div className="md:col-span-2">
          <Field label="Email" required>
            <div className="relative">
              <Input value={f.email} onChange={e=>set('email',e.target.value)} className={emailOk ? '' : '!border-rose-300 !bg-rose-50/40'}/>
              {!emailOk && <p className="text-[11.5px] text-rose-600 font-semibold mt-1.5">Enter a valid email address</p>}
            </div>
          </Field>
        </div>
        <div className="md:col-span-2">
          <Field label="Phone number">
            <div className="flex items-center gap-2">
              <Select value={f.cc} onChange={e=>set('cc',e.target.value)} className="!w-24">
                {['+91','+1','+44','+61','+34'].map(c=><option key={c}>{c}</option>)}
              </Select>
              <Input value={f.phone} onChange={e=>set('phone',e.target.value)} placeholder="Phone number"/>
            </div>
          </Field>
        </div>
      </div>
      <div className="max-w-3xl rounded-2xl border border-rose-200 bg-rose-50/40 px-5 py-4 flex items-center justify-between gap-4 flex-wrap">
        <div>
          <p className="text-[13.5px] font-bold text-ink">Delete account</p>
          <p className="text-[12px] text-ink-muted mt-0.5">Permanently removes your account, campaigns and review data.</p>
        </div>
        <button onClick={()=>{ if(confirmDel){ setConfirmDel(false); } else { setConfirmDel(true); setTimeout(()=>setConfirmDel(false), 3500); } }}
          className={"rounded-full px-4 py-2 text-[12.5px] font-bold border transition-colors "+(confirmDel ? "bg-rose-600 text-white border-rose-600" : "text-rose-600 border-rose-300 hover:bg-rose-50")}>
          {confirmDel ? 'Click again to confirm' : 'Delete account'}
        </button>
      </div>
    </div>
  );
}

/* ── Billing tab (production) ─────────────────────────────────────────── */
function SettingsBillingV2() {
  const [tCur, setTCur] = React.useState('INR');
  const TOPUPS = {
    INR: [ { r:25, p:'₹599', per:'₹24' }, { r:100, p:'₹1,899', per:'₹19', pop:true }, { r:250, p:'₹3,999', per:'₹16' } ],
    USD: [ { r:25, p:'$12', per:'$0.48' }, { r:100, p:'$39', per:'$0.39', pop:true }, { r:250, p:'$79', per:'$0.32' } ],
  };
  return (
    <div className="space-y-7">
      <div>
        <h3 className="text-[16px] font-bold text-ink flex items-center gap-2">Plans &amp; Billing <InfoTip text="Your current subscription, one-time review top-ups, payment method and past invoices."/></h3>
        <p className="text-[12.5px] text-ink-muted mt-0.5">Manage your subscription, payment method and invoices.</p>
      </div>
      <div className="rounded-2xl border border-line p-5">
        <div className="flex items-start justify-between gap-4 flex-wrap">
          <div>
            <div className="flex items-center gap-2">
              <p className="text-[15px] font-extrabold text-ink">Free plan</p>
              <span className="inline-flex items-center gap-1.5 text-[10.5px] font-bold px-2 py-0.5 rounded-full bg-green-50 text-green-700"><span className="w-1.5 h-1.5 rounded-full bg-green-500"></span>Active</span>
            </div>
            <p className="text-[12.5px] text-ink-muted mt-1">10 reviews per month · no billing date, free forever</p>
          </div>
          <BtnPrimary onClick={()=>window.__openPricing && window.__openPricing()}>Upgrade plan</BtnPrimary>
        </div>
        <div className="mt-4 pt-4 border-t border-line/70">
          <div className="flex items-baseline justify-between text-[12px]">
            <span className="font-semibold text-ink">Monthly usage</span>
            <span className="text-ink-muted">8 of 10 reviews · resets 1 Aug 2026</span>
          </div>
          <div className="mt-2 h-2 rounded-full bg-surface-input overflow-hidden">
            <div className="h-full rounded-full" style={{width:'80%',background:'linear-gradient(90deg,var(--accent),var(--accent-dark))'}}></div>
          </div>
        </div>
      </div>
      <div>
        <div className="flex items-center justify-between mb-1">
          <h4 className="text-[13.5px] font-bold text-ink flex items-center gap-2">Review top-ups <InfoTip text="One-time packs of extra reviews for when you hit your monthly plan limit — they never expire and don\u2019t change your plan."/></h4>
          <div className="flex items-center gap-2">
            <div className="inline-flex items-center gap-1 rounded-lg bg-surface-input p-0.5" title="Demo only — currency follows the seller's account country">
              {[['INR','🇮🇳 ₹'],['USD','🌍 $']].map(([v,l])=>(
                <button key={v} onClick={()=>setTCur(v)} className={"px-2.5 py-1 rounded-md text-[11px] font-bold transition-colors "+(tCur===v?'bg-white text-ink shadow-soft':'text-ink-soft hover:text-ink')}>{l}</button>
              ))}
            </div>
            <span className="text-[11px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-full bg-surface-input text-ink-muted">One-time</span>
          </div>
        </div>
        <p className="text-[12px] text-ink-muted mb-3">Hit your monthly limit? Buy extra reviews anytime — no plan change, they never expire.</p>
        <div className="grid sm:grid-cols-3 gap-3">
          {TOPUPS[tCur].map(t=>(
            <div key={t.r} className={"relative rounded-2xl border p-4 flex flex-col gap-1 "+(t.pop?'border-brand/40 bg-brand/[0.03]':'border-line')}>
              {t.pop && <span className="absolute -top-2 right-3 text-[9.5px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-full acc-bg text-white">Popular</span>}
              <p className="text-[18px] font-extrabold text-ink leading-none">+{t.r} <span className="text-[12px] font-semibold text-ink-muted">reviews</span></p>
              <p className="text-[13px] font-bold acc-text">{t.p} <span className="text-[11px] font-normal text-ink-soft">· {t.per}/review</span></p>
              <button onClick={()=>window.rbToast && window.rbToast('Top-up added to checkout (demo)')} className="mt-2 h-8 rounded-lg text-[12px] font-bold border border-brand/30 text-brand hover:bg-brand/5 transition">Buy pack</button>
            </div>
          ))}
        </div>
      </div>
      <div>
        <h4 className="text-[13.5px] font-bold text-ink mb-3">Payment method</h4>
        <div className="rounded-2xl border border-dashed border-gray-300 px-5 py-4 flex items-center justify-between gap-4 flex-wrap">
          <div className="flex items-center gap-3">
            <span className="w-10 h-7 rounded-md bg-surface-input border border-line flex items-center justify-center">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-ink-soft"><rect x="2" y="5" width="20" height="14" rx="2"/><path d="M2 10h20"/></svg>
            </span>
            <p className="text-[12.5px] text-ink-muted">No payment method on file — you'll add one when upgrading.</p>
          </div>
          <BtnGhost>Add card</BtnGhost>
        </div>
      </div>
      <div>
        <div className="flex items-center justify-between mb-3">
          <h4 className="text-[13.5px] font-bold text-ink">Invoices</h4>
          <button className="text-[12.5px] font-bold acc-text hover:opacity-80">Download CSV</button>
        </div>
        <div className="rounded-2xl border border-line px-5 py-10 text-center">
          <p className="text-[13px] font-semibold text-ink">No invoices yet</p>
          <p className="text-[12px] text-ink-muted mt-1">Invoices appear here after your first paid billing cycle.</p>
        </div>
      </div>
    </div>
  );
}

/* ── Password tab (production) ────────────────────────────────────────── */
function SettingsPasswordV2() {
  const [oldPw, setOldPw]   = React.useState('');
  const [pw, setPw]         = React.useState('');
  const [pw2, setPw2]       = React.useState('');
  const [show, setShow]     = React.useState(false);
  const [saved, setSaved]   = React.useState(false);
  const checks = [
    { ok: pw.length >= 8,        label:'At least 8 characters' },
    { ok: /[0-9]/.test(pw),      label:'Contains a number' },
    { ok: /[^A-Za-z0-9]/.test(pw), label:'Contains a symbol' },
    { ok: pw.length > 0 && pw === pw2, label:'Passwords match' },
  ];
  const strength = checks.slice(0,3).filter(c=>c.ok).length;
  const valid = oldPw.length > 0 && checks.every(c=>c.ok);
  const update = () => { setSaved(true); setOldPw(''); setPw(''); setPw2(''); setTimeout(()=>setSaved(false), 2500); };
  const PwInput = ({ value, onChange, placeholder }) => (
    <input type={show ? 'text' : 'password'} value={value} onChange={onChange} placeholder={placeholder}
      className="w-full bg-surface-input border border-transparent rounded-xl px-4 py-3 text-[14px] text-ink placeholder:text-ink-soft outline-none focus:bg-white focus:border-brand-200 acc-ring transition"/>
  );
  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between gap-3">
        <div>
          <h3 className="text-[16px] font-bold text-ink">Password &amp; security</h3>
          <p className="text-[12.5px] text-ink-muted mt-0.5">Use a strong password you don't use anywhere else.</p>
        </div>
        <SavedFlash show={saved}/>
      </div>
      <div className="space-y-4 max-w-md">
        <Field label="Current password" required>{PwInput({ value:oldPw, onChange:e=>setOldPw(e.target.value), placeholder:'Enter your current password' })}</Field>
        <Field label="New password" required>
          {PwInput({ value:pw, onChange:e=>setPw(e.target.value), placeholder:'Enter a new password' })}
        </Field>
        {pw.length > 0 && (
          <div className="flex gap-1.5">
            {[0,1,2].map(i=>(
              <div key={i} className="h-1.5 flex-1 rounded-full transition-colors"
                   style={{background: i < strength ? (strength===1?'#EF4444':strength===2?'#F59E0B':'#1FB866') : '#ECE9E3'}}></div>
            ))}
          </div>
        )}
        <Field label="Confirm new password" required>{PwInput({ value:pw2, onChange:e=>setPw2(e.target.value), placeholder:'Repeat the new password' })}</Field>
        <div className="space-y-1.5">
          {checks.map(c=>(
            <p key={c.label} className={"text-[12px] flex items-center gap-2 "+(c.ok?"text-green-600 font-semibold":"text-ink-soft")}>
              <svg width="11" height="11" 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>
              {c.label}
            </p>
          ))}
        </div>
        <label className="inline-flex items-center gap-2 text-[12.5px] text-ink-muted cursor-pointer select-none">
          <input type="checkbox" checked={show} onChange={e=>setShow(e.target.checked)} className="w-3.5 h-3.5 accent-[var(--accent)]"/>
          Show passwords
        </label>
        <div className="pt-1">
          <BtnPrimary disabled={!valid} onClick={update}>Update password</BtnPrimary>
        </div>
      </div>
    </div>
  );
}

/* ── Affiliate Payouts tab — wallet + transactions ──────────────────── */
const WALLET_TXNS = {
  IN: [
    { d:'Jul 20, 2026', desc:'Commission · Kavya Home Labs (Growth)',  amt:'+₹500', state:'Available' },
    { d:'Jul 12, 2026', desc:'Commission · Nutriblend Foods (Starter)', amt:'+₹200', state:'Pending' },
    { d:'Jun 30, 2026', desc:'Withdrawal · UPI ····@okaxis',            amt:'−₹1,200', state:'Paid out' },
    { d:'Jun 20, 2026', desc:'Commission · Kavya Home Labs (Growth)',  amt:'+₹500', state:'Withdrawn' },
    { d:'Jun 12, 2026', desc:'Commission · Voltix Audio (Growth)',     amt:'+₹500', state:'Withdrawn' },
    { d:'May 20, 2026', desc:'Commission · Kavya Home Labs (Growth)',  amt:'+₹200', state:'Withdrawn' },
  ],
  INTL: [
    { d:'Jul 18, 2026', desc:'Commission · Nordica Living, Spain (Growth)', amt:'+$18', state:'Available' },
    { d:'Jul 2, 2026',  desc:'Commission · Nordica Living, Spain (Starter)', amt:'+$7', state:'Pending' },
    { d:'Jun 15, 2026', desc:'Commission · Baltik Home, Poland (Growth)', amt:'+$18', state:'Withdrawn' },
  ],
};
const TXN_CLS = {
  Available:  'bg-emerald-50 text-emerald-700',
  Pending:    'bg-amber-50 text-amber-700',
  'Paid out': 'bg-sky-50 text-sky-700',
  Withdrawn:  'bg-gray-100 text-gray-500',
};
function SettingsPayoutsV2() {
  const toast = (m) => window.rbToast ? window.rbToast(m) : null;
  const [region, setRegion] = React.useState('IN');   // demo-only switch — real app uses seller's account country
  const W = region === 'IN'
    ? { flag:'🇮🇳', lb:'Wallet', cur:'INR', avail:'₹500', pend:'₹200', life:'₹1,900', min:'₹5,000', can:false, name:'payout-inr', opts:['UPI','GPay'] }
    : { flag:'🌍', lb:'Wallet', cur:'USD', avail:'$18', pend:'$7', life:'$25', min:'$100', can:false, name:'payout-usd', opts:['PayPal','Wise','Payoneer'] };
  const txns = WALLET_TXNS[region];
  const [method, setMethod] = React.useState(W.opts[0]);
  React.useEffect(()=>{ setMethod(W.opts[0]); }, [region]);
  const detail = region==='IN'
    ? (method==='UPI' ? { lb:'UPI ID', ph:'yourname@okhdfc' } : { lb:'GPay number', ph:'+91 98765 43210' })
    : { lb:method+' email', ph:'you@example.com' };
  return (
    <div className="space-y-6">
      <div className="flex items-start justify-between gap-4">
        <div>
          <h3 className="text-[16px] font-extrabold text-ink flex items-center gap-2">Affiliate Payouts <InfoTip text="Cash commissions earned from referring other sellers. Withdraw your full balance once you cross the minimum."/></h3>
          <p className="text-[12.5px] text-ink-muted mt-0.5">All Refer &amp; Earn commissions land in this wallet. Pending amounts clear 30 days after the referred seller's payment.</p>
        </div>
        <div className="shrink-0 inline-flex items-center gap-1 rounded-lg bg-surface-input p-0.5" title="Demo only — wallet follows the seller's account country">
          {[['IN','🇮🇳 India'],['INTL','🌍 Intl']].map(([v,l])=>(
            <button key={v} onClick={()=>setRegion(v)} className={"px-2.5 py-1 rounded-md text-[11px] font-bold transition-colors "+(region===v?'bg-white text-ink shadow-soft':'text-ink-soft hover:text-ink')}>{l}</button>
          ))}
        </div>
      </div>
      {/* Wallet — seller sees only their region's wallet */}
      <div className="rounded-2xl border border-line bg-surface-subtle p-5 flex flex-col sm:flex-row sm:items-center gap-5">
        <div className="flex-1 grid grid-cols-3 gap-4">
          <div><p className="text-[11px] font-semibold uppercase tracking-wider text-ink-muted">Available</p><p className="text-[24px] font-extrabold text-ink mt-1 leading-none">{W.avail}</p></div>
          <div><p className="text-[11px] font-semibold uppercase tracking-wider text-ink-muted">Pending</p><p className="text-[24px] font-extrabold text-ink mt-1 leading-none">{W.pend}</p></div>
          <div><p className="text-[11px] font-semibold uppercase tracking-wider text-ink-muted">Lifetime earned</p><p className="text-[24px] font-extrabold acc-text mt-1 leading-none">{W.life}</p></div>
        </div>
        <div className="shrink-0 text-right">
          <button disabled className="h-10 px-5 rounded-xl text-[13px] font-bold text-white bg-brand-200 cursor-not-allowed" title={'Minimum '+W.min}>Withdraw {W.avail}</button>
          <p className="text-[11px] text-ink-soft mt-1.5">Minimum {W.min} · full balance in one request</p>
        </div>
      </div>
      {/* Payout method */}
      <div>
        <p className="text-[12px] font-bold text-ink mb-2">Payout method <span className="font-normal text-ink-muted">· paid within 48 hours of approval</span></p>
        <div className="flex items-center gap-2 flex-wrap">
          {W.opts.map((m)=>(
            <label key={m} className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-line text-[12px] font-semibold text-ink-muted cursor-pointer has-[:checked]:border-brand has-[:checked]:text-brand has-[:checked]:bg-brand/5 transition">
              <input type="radio" name={W.name} checked={method===m} onChange={()=>setMethod(m)} className="accent-current w-3 h-3"/>{m}
            </label>
          ))}
        </div>
        <div className="mt-3 flex items-center gap-2 max-w-md">
          <div className="flex-1">
            <Input key={method} placeholder={detail.lb+' · '+detail.ph}/>
          </div>
          <button onClick={()=>toast('Payout details saved (demo)')} className="shrink-0 px-3.5 py-2.5 rounded-lg border border-brand/30 text-brand text-[12px] font-bold hover:bg-brand/5 transition">Save</button>
        </div>
      </div>
      {/* Transactions */}
      <div>
        <p className="text-[12px] font-bold text-ink mb-2">Transactions</p>
        <div className="rounded-xl border border-line overflow-hidden">
          <div className="grid items-center gap-3 px-4 py-2.5 bg-surface-subtle text-[11px] font-semibold uppercase tracking-wider text-ink-muted" style={{gridTemplateColumns:'110px 1fr 80px 100px'}}>
            <span>Date</span><span>Description</span><span className="text-right">Amount</span><span className="text-center">Status</span>
          </div>
          <div className="divide-y divide-gray-100">
            {WALLET_TXNS[region].map((t,i)=>(
              <div key={i} className="grid items-center gap-3 px-4 py-3" style={{gridTemplateColumns:'110px 1fr 80px 100px'}}>
                <p className="text-[12px] text-ink-soft">{t.d}</p>
                <p className="text-[12.5px] font-semibold text-ink truncate">{t.desc}</p>
                <p className={"text-[13px] font-bold text-right " + (t.amt.startsWith('−') ? 'text-ink-muted' : 'text-ink')}>{t.amt}</p>
                <span className={"inline-flex justify-center px-2 py-1 rounded-full text-[11px] font-bold " + TXN_CLS[t.state]}>{t.state}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function SettingsV2({ subRoute, onSubNav }) {
  const tab = SET_TABS_V2.find(t => t.id === subRoute) ? subRoute : 'account';
  return (
    <>
      <PageHeader title="Settings"/>
      <div className="px-7 py-6 grid lg:grid-cols-[240px_1fr] gap-6 items-start">
        <Card className="p-2">
          {SET_TABS_V2.map(t => {
            const on = tab === t.id;
            return (
              <button key={t.id} onClick={() => onSubNav(t.id)}
                className={"w-full text-left px-3.5 py-3 rounded-xl flex items-center gap-3 transition-colors "+(on ? "acc-bg-soft" : "hover:bg-surface-subtle")}>
                <span className={"shrink-0 "+(on?"acc-text":"text-ink-soft")}>{t.icon}</span>
                <span className="min-w-0">
                  <span className={"block text-[13.5px] font-bold leading-tight "+(on?"acc-text":"text-ink")}>{t.label}</span>
                  <span className="block text-[11.5px] text-ink-muted mt-0.5">{t.d}</span>
                </span>
              </button>
            );
          })}
        </Card>
        {tab === 'brand'
          ? <SettingsBrandV2/>
          : (
            <Card className="p-6 min-h-[420px]">
              {tab === 'account'  && <SettingsAccountV2/>}
              {tab === 'billing'  && <SettingsBillingV2/>}
              {tab === 'password' && <SettingsPasswordV2/>}
              {tab === 'payouts'  && <SettingsPayoutsV2/>}
            </Card>
          )}
      </div>
    </>
  );
}

window.Settings = SettingsV2;
