// Business — three partner offerings, switchable. Reached via the top-bar
// "For business" link. The "Sell in the US" tab carries a grouped, selectable
// service picker with pricing folded into the selection (expand any card for
// detail + tunable inputs); a live setup/monthly estimate builds as you pick.
//
// The picker (BizServicePicker) is bilingual: pass lang="ar" (the /launch-in-us
// landing does, in RTL) to render Arabic labels. Prices/numerals stay Latin in
// Geist Mono per the brand guideline; the homepage uses the English default.

const { useState: bizS, useMemo: bizMemo } = React;

const BIZ_OFFERS = [
{
  id: 'us', tab: 'Sell in the US', hue: 240,
  who: 'For international brands ready to cross the border.',
  title: 'Sell in the <em>US.</em>',
  desc: "We take your product from a factory abroad to a US doorstep — the freight, the paperwork, the shelf presence. You make it; we land it.",
  cta: 'Bring my brand to the US', send: "I'd like to sell my brand in the US with blyzr"
},
{
  id: 'launch', tab: 'Launch product', hue: 135,
  who: 'For indie chefs and first-time founders.',
  title: 'Launch your <em>product.</em>',
  desc: "A recipe in your kitchen isn't a product on a shelf — yet. We help you cross that gap, from getting the formula right to getting it into hands.",
  services: [
  { icon: 'chart', label: 'Market study', sub: 'demand, pricing, positioning' },
  { icon: 'recipe', label: 'Formula', sub: 'recipe-to-spec & shelf life' },
  { icon: 'box', label: 'Packaging', sub: 'design, sourcing, compliance' },
  { icon: 'truck', label: 'Distribution', sub: 'channels and logistics' },
  { icon: 'pantry', label: 'Storage', sub: 'warehousing and stock' }],

  cta: 'Launch with blyzr', send: "I'm an indie chef and want to launch a product with blyzr"
},
{
  id: 'with', tab: 'Sell with us', hue: 55,
  who: 'For established local brands.',
  title: 'Sell <em>with us.</em>',
  desc: "You already have a product people love. We help it reach more of them — onto blyzr and beyond, handled end to end.",
  services: [
  { icon: 'chart', label: 'Market study', sub: 'where you grow next' },
  { icon: 'box', label: 'Packaging', sub: 'retail-ready refinement' },
  { icon: 'truck', label: 'Distribution', sub: 'wider reach, same quality' },
  { icon: 'pantry', label: 'Storage', sub: 'warehousing and stock' }],

  cta: 'Sell with blyzr', send: "My local brand wants to sell with blyzr"
}];


// ---- Sell-in-the-US service model (selection + pricing in one) -------------
// Each group/item carries an Arabic twin (_ar) used when the picker is in Arabic.
const US_PLAN = [
{
  id: 'logi', label: 'Shipping & logistics', label_ar: 'الشحن واللوجستيات', hue: 240,
  blurb: 'Across the border and onto a US shelf.', blurb_ar: 'عبر الحدود وإلى رفٍّ أمريكي.',
  items: [
  { id: 'ship', icon: 'truck', name: 'Shipping & customs', name_ar: 'الشحن والجمارك',
    sub: 'Freight, clearance, duties, FDA.', sub_ar: 'شحن، تخليص، رسوم، FDA.',
    more: 'Ocean freight from your factory, US customs clearance, duties and FDA import paperwork — handled door to dock.',
    more_ar: 'شحنٌ بحري من مصنعك، وتخليصٌ جمركي أمريكي، ورسومٌ وأوراق استيراد FDA — من الباب إلى الرصيف.',
    setup: 2000, unit: { key: 'containers', label: 'Containers', label_ar: 'حاويات', per: 500, target: 'setup', min: 1, max: 12, def: 2, perLabel: '/ container', perLabel_ar: '/ حاوية' } },
  { id: 'storage', icon: 'pantry', name: 'Logistics & storage', name_ar: 'اللوجستيات والتخزين',
    sub: 'Warehousing & inventory.', sub_ar: 'تخزينٌ وجرد.',
    more: 'Receiving, climate-controlled warehousing and order forwarding from our US facility, with live inventory counts.',
    more_ar: 'استلامٌ وتخزينٌ مُكيّف وإعادة توجيه الطلبات من منشأتنا الأمريكية، مع جردٍ مباشر.',
    monthly: 3500 },
  { id: 'fulfil', icon: 'basket', name: 'Fulfilment', name_ar: 'التنفيذ',
    sub: 'Pick, pack, ship, returns.', sub_ar: 'التقاط، تغليف، شحن، مرتجعات.',
    more: 'We pick, pack and ship every order the moment it lands — branded, tracked, and returns coordinated.',
    more_ar: 'نلتقط ونغلّف ونشحن كلَّ طلبٍ فور وصوله — بعلامتك، ومتتبَّعًا، ومع تنسيق المرتجعات.',
    monthly: 1000, unit: { key: 'orders', label: 'Orders / month', label_ar: 'طلبات / شهر', per: 2, target: 'monthly', min: 0, max: 5000, step: 50, def: 600, perLabel: '/ order', perLabel_ar: '/ طلب' } }]

},
{
  id: 'mktg', label: 'Marketing & sales', label_ar: 'التسويق والمبيعات', hue: 200,
  blurb: 'Turning shelf presence into orders.', blurb_ar: 'نحوّل الحضور على الرفّ إلى طلبات.',
  items: [
  { id: 'store', icon: 'store', name: 'Storefronts', name_ar: 'المتاجر',
    sub: 'Amazon, TikTok Shop, Walmart, your own.', sub_ar: 'أمازون، تيك توك شوب، وولمارت، ومتجرك.',
    more: 'A branded store built and run for you on the major marketplaces and your own domain — design, content and SEO included.',
    more_ar: 'متجرٌ بعلامتك نبنيه وندير​ه لك على المتاجر الكبرى ونطاقك الخاص — التصميم والمحتوى وتحسين الظهور مشمولة.',
    setup: 4000 },
  { id: 'content', icon: 'recipe', name: 'Content & video', name_ar: 'المحتوى والفيديو',
    sub: 'Photography, short-form, creators.', sub_ar: 'تصوير، فيديو قصير، صنّاع محتوى.',
    more: 'Product photography, short-form video and creator-style content, shot and posted on a steady cadence.',
    more_ar: 'تصوير المنتجات، وفيديو قصير، ومحتوى بأسلوب صنّاع المحتوى — يُصوَّر ويُنشَر بوتيرةٍ ثابتة.',
    monthly: 2000 },
  { id: 'growth', icon: 'megaphone', name: 'Marketing & growth', name_ar: 'التسويق والنمو',
    sub: 'Campaigns, placement, paid media.', sub_ar: 'حملات، توزيع، إعلانات مدفوعة.',
    more: 'Launch campaigns, retail placement and paid media — planned and managed. Our fee scales with your ad spend.',
    more_ar: 'حملات إطلاق، وتوزيعٌ في المتاجر، وإعلاناتٌ مدفوعة — تُخطَّط وتُدار. وأجرتنا تتناسب مع إنفاقك الإعلاني.',
    monthly: 3000, unit: { key: 'spend', label: 'Monthly ad spend', label_ar: 'الإنفاق الإعلاني الشهري', per: 0.15, target: 'monthly', min: 0, max: 60000, step: 1000, def: 10000, money: true, perLabel: '15% of spend', perLabel_ar: '15% من الإنفاق' } }]

},
{
  id: 'brand', label: 'Brand & compliance', label_ar: 'العلامة والامتثال', hue: 150,
  blurb: 'The paperwork that makes you legit.', blurb_ar: 'الأوراق التي تجعلك رسميًا.',
  items: [
  { id: 'fda', icon: 'globe', name: 'FDA registration', name_ar: 'تسجيل FDA',
    sub: 'Facility & product registration.', sub_ar: 'تسجيل المنشأة والمنتج.',
    more: 'Facility and product registration so you can legally sell food in the US, plus ongoing renewal reminders.',
    more_ar: 'تسجيل المنشأة والمنتج لتبيع الغذاء قانونيًا في أمريكا، مع تذكيراتٍ بالتجديد.',
    setup: 1000 },
  { id: 'tm', icon: 'box', name: 'Trademark', name_ar: 'العلامة التجارية',
    sub: 'Protect your brand & mark.', sub_ar: 'احمِ اسمك وعلامتك.',
    more: 'US trademark search and filing that protects your brand name and mark from copycats.',
    more_ar: 'بحثٌ وتسجيلٌ لعلامةٍ تجارية أمريكية يحمي اسم علامتك من المقلّدين.',
    setup: 2000 },
  { id: 'label', icon: 'chart', name: 'Label review', name_ar: 'مراجعة الملصق',
    sub: 'Nutrition, ingredient & claims.', sub_ar: 'تغذية، مكوّنات، ادّعاءات.',
    more: 'Nutritional panel, ingredient and marketing-claim review so every label meets US compliance.',
    more_ar: 'مراجعة الجدول الغذائي والمكوّنات والادّعاءات التسويقية لتطابق كلّ ملصقٍ مع الامتثال الأمريكي.',
    setup: 1200 }]

}];

const US_ITEMS = US_PLAN.flatMap((g) => g.items.map((it) => ({ ...it, hue: g.hue })));

const usd = (n) => '$' + Math.round(n).toLocaleString('en-US');

// UI chrome strings for the picker, by language.
const PLAN_T = {
  en: {
    eyebrow: 'Your estimate', setup: 'One-time setup', monthly: 'Then / month', request: 'Request my plan',
    fine: 'Indicative only — a real person reworks this with you on a call.',
    mo: '/mo', once: ' once', moLine: ' / mo', flat: 'flat rate', moreTitle: 'Tell me more', lessTitle: 'Less',
    sel: (n) => `${n} ${n === 1 ? 'service' : 'services'} selected`,
    leadTitle: 'Request your US plan', leadInterest: 'Sell in the US',
    sumHead: (n) => `US plan — ${n} ${n === 1 ? 'service' : 'services'}`,
    sumTotal: (s, m) => `Total: ${s} setup + ${m}/mo`,
  },
  ar: {
    eyebrow: 'تقديرك', setup: 'تأسيس لمرة واحدة', monthly: 'ثمّ / شهريًا', request: 'اطلب خطتي',
    fine: 'تقديريٌّ فقط — يعيد شخصٌ حقيقي صياغته معك في مكالمة.',
    mo: '/شهر', once: ' مرة', moLine: ' / شهر', flat: 'سعر ثابت', moreTitle: 'أخبرني أكثر', lessTitle: 'أقل',
    sel: (n) => (n === 1 ? 'خدمة واحدة مُختارة' : `${n} خدمات مُختارة`),
    leadTitle: 'اطلب خطتك الأمريكية', leadInterest: 'البيع في أمريكا',
    sumHead: (n) => `خطة أمريكا — ${n === 1 ? 'خدمة واحدة' : `${n} خدمات`}`,
    sumTotal: (s, m) => `الإجمالي: ${s} تأسيس + ${m}/شهر`,
  },
};

// compute { setup, monthly, detail } for one item given its tuned values
const priceUS = (it, v, lang = 'en') => {
  let setup = it.setup || 0,monthly = it.monthly || 0,detail = '';
  if (it.unit) {
    const q = v[it.unit.key] ?? it.unit.def;
    const add = it.unit.per * q;
    if (it.unit.target === 'monthly') monthly += add;else setup += add;
    if (it.unit.money) {
      detail = lang === 'ar' ? `15% من ${usd(q)}` : `15% of ${usd(q)} spend`;
    } else {
      const lbl = lang === 'ar' ? it.unit.label_ar || it.unit.label : it.unit.label.toLowerCase();
      detail = `${q} ${lbl}`;
    }
  }
  return { setup, monthly, detail };
};

const BizStepper = ({ u, value, set }) =>
<div className="calc-stepper">
    <button onClick={() => set(Math.max(u.min, value - (u.step || 1)))} disabled={value <= u.min}>{Icon.minus({})}</button>
    <span className="calc-step-n mono">{value.toLocaleString('en-US')}</span>
    <button onClick={() => set(Math.min(u.max, value + (u.step || 1)))} disabled={value >= u.max}>{Icon.plus({})}</button>
  </div>;

const BizRange = ({ u, value, set }) =>
<input type="range" className="calc-slider" min={u.min} max={u.max} step={u.step || 1} value={value}
onChange={(e) => set(Number(e.target.value))} />;


const BizCard = ({ it, on, open, v, toggleSel, toggleOpen, setVal, lang = 'en' }) => {
  const t = PLAN_T[lang];
  const ar = lang === 'ar';
  const p = priceUS(it, v, lang);
  const isMo = p.monthly > 0;
  const amt = isMo ? p.monthly : p.setup;
  const name = ar ? it.name_ar || it.name : it.name;
  const sub = ar ? it.sub_ar || it.sub : it.sub;
  const more = ar ? it.more_ar || it.more : it.more;
  const uLabel = it.unit ? ar ? it.unit.label_ar || it.unit.label : it.unit.label : '';
  const uPer = it.unit ? ar ? it.unit.perLabel_ar || it.unit.perLabel : it.unit.perLabel : '';
  return (
    <div className={`biz-pick-card ${on ? 'on' : ''} ${open ? 'open' : ''}`} style={{ '--h': it.hue }} onClick={() => toggleSel(it.id)}>
      <div className="biz-pick-row">
        <span className="biz-pick-ic">{Icon[it.icon]({})}</span>
        <span className="biz-pick-text">
          <span className="biz-pick-name">{name}</span>
          <span className="biz-pick-sub">{sub}</span>
        </span>
        <button className="biz-pick-more" title={open ? t.lessTitle : t.moreTitle} onClick={(e) => {e.stopPropagation();toggleOpen(it.id);}}>
          {open ? Icon.minus({}) : Icon.plus({})}
        </button>
        <span className="biz-pick-check">{Icon.check({})}</span>
        <span className="biz-pick-price mono">{usd(amt)}<small>{isMo ? t.mo : t.once}</small></span>
      </div>

      {open &&
      <div className="biz-pick-detail" onClick={(e) => e.stopPropagation()}>
          <p className="biz-pick-moretext">{more}</p>
          {it.unit &&
        <div className="calc-control">
              <div className="calc-control-top">
                <span className="calc-control-label">{uLabel}</span>
                <span className="calc-control-meta mono">{it.unit.money ? uPer : `${usd(it.unit.per)} ${uPer}`}</span>
              </div>
              {it.unit.max <= 12 ?
          <BizStepper u={it.unit} value={v[it.unit.key] ?? it.unit.def} set={(n) => setVal(it.id, it.unit.key, n)} /> :
          <>
                    <BizRange u={it.unit} value={v[it.unit.key] ?? it.unit.def} set={(n) => setVal(it.id, it.unit.key, n)} />
                    <div className="calc-slider-val mono">{it.unit.money ? usd(v[it.unit.key] ?? it.unit.def) : (v[it.unit.key] ?? it.unit.def).toLocaleString('en-US')}</div>
                  </>}
            </div>
        }
          <div className="biz-pick-line">
            <span className={ar ? 'biz-pick-q' : 'mono'}>{p.detail || t.flat}</span>
            <span className="mono">{usd(amt)}<small>{isMo ? t.moLine : t.once}</small></span>
          </div>
        </div>
      }
    </div>);

};

const BizServicePicker = ({ onLead, lang = 'en' }) => {
  const t = PLAN_T[lang];
  const ar = lang === 'ar';
  // Start with an empty plan ($0) — the visitor builds it up from nothing.
  const init = {};
  US_ITEMS.forEach((it) => {init[it.id] = false;});
  const [sel, setSel] = bizS(init);
  const [vals, setVals] = bizS({});
  const [open, setOpen] = bizS({});

  const toggleSel = (id) => setSel((s) => ({ ...s, [id]: !s[id] }));
  const toggleOpen = (id) => setOpen((s) => ({ ...s, [id]: !s[id] }));
  const setVal = (id, key, n) => setVals((s) => ({ ...s, [id]: { ...(s[id] || {}), [key]: n } }));

  const { setup, monthly, count } = bizMemo(() => {
    let su = 0,mo = 0,c = 0;
    US_ITEMS.forEach((it) => {
      if (!sel[it.id]) return;
      c++;
      const p = priceUS(it, vals[it.id] || {});
      su += p.setup;mo += p.monthly;
    });
    return { setup: su, monthly: mo, count: c };
  }, [sel, vals]);

  return (
    <div className="biz-pick" dir={ar ? 'rtl' : 'ltr'}>
      <div className="biz-pick-main">
        {US_PLAN.map((g) => {
          const n = g.items.filter((it) => sel[it.id]).length;
          return (
            <div key={g.id} className="biz-pick-group" style={{ '--h': g.hue }}>
              <div className="biz-pick-head">
                <span className="biz-pick-dot" />
                <div className="biz-pick-headtext">
                  <span className="biz-pick-label">{ar ? g.label_ar || g.label : g.label}</span>
                  <span className="biz-pick-blurb">{ar ? g.blurb_ar || g.blurb : g.blurb}</span>
                </div>
                <span className="biz-pick-count mono" dir="ltr">{n}/{g.items.length}</span>
              </div>
              <div className="biz-pick-cards">
                {g.items.map((it) =>
                <BizCard key={it.id} it={{ ...it, hue: g.hue }}
                on={!!sel[it.id]} open={!!open[it.id]} v={vals[it.id] || {}}
                toggleSel={toggleSel} toggleOpen={toggleOpen} setVal={setVal} lang={lang} />
                )}
              </div>
            </div>);

        })}
      </div>

      <aside className="biz-pick-side">
        <div className="biz-pick-sum glass">
          <div className="biz-pick-sum-eyebrow mono">{t.eyebrow}</div>
          <div className="biz-pick-sum-figs">
            <div className="biz-pick-fig">
              <span className="biz-pick-fig-k mono">{t.setup}</span>
              <span className="biz-pick-fig-v" dir="ltr">{usd(setup)}</span>
            </div>
            <div className="biz-pick-fig">
              <span className="biz-pick-fig-k mono">{t.monthly}</span>
              <span className="biz-pick-fig-v" dir="ltr">{usd(monthly)}</span>
            </div>
          </div>
          <div className="biz-pick-barcount mono">{t.sel(count)}</div>
          <button className="btn btn-accent" style={{ width: '100%', justifyContent: 'center' }} disabled={!count}
          onClick={() => {
            // In Arabic the summary is RTL; isolate each $-price (U+2066…U+2069) so it
            // doesn't get reordered to "3,000$" inside the surrounding Arabic text.
            const wrap = ar ? (s) => `\u2066${s}\u2069` : (s) => s;
            const lines = US_ITEMS.filter((it) => sel[it.id]).map((it) => {
              const pr = priceUS(it, vals[it.id] || {}, lang);
              const mo = pr.monthly > 0;
              const nm = ar ? it.name_ar || it.name : it.name;
              return `• ${nm}${pr.detail ? ` (${pr.detail})` : ''} — ${wrap(usd(mo ? pr.monthly : pr.setup))}${mo ? t.mo : t.once}`;
            });
            onLead({ title: t.leadTitle, interest: t.leadInterest, kind: 'quote',
              summary: `${t.sumHead(count)}\n${lines.join('\n')}\n${t.sumTotal(wrap(usd(setup)), wrap(usd(monthly)))}` });
          }}>
            {t.request} <Icon.arrow style={{ width: 14, height: 14, transform: ar ? 'scaleX(-1)' : 'none' }} />
          </button>
          <p className="biz-pick-fine">{t.fine}</p>
        </div>
      </aside>
    </div>);

};

const Business = ({ onSend, onHome }) => {
  const [i, setI] = bizS(0);
  const o = BIZ_OFFERS[i];
  const isUS = o.id === 'us';
  const [lead, setLead] = bizS(null);

  return (
    <>
      {/* Offer switch */}
      <div className="biz-tabs">
        {BIZ_OFFERS.map((x, idx) =>
        <button key={x.id} className={`biz-tab ${i === idx ? 'active' : ''}`} onClick={() => setI(idx)}>
            {x.tab}
          </button>
        )}
      </div>

      {/* Active offer */}
      <div className="biz-panel" style={{ '--h': o.hue }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 14 }}>{o.who}</div>
          <h2 className="biz-title" dangerouslySetInnerHTML={{ __html: o.title }} />
          <p className="biz-desc">{o.desc}</p>
        </div>
        <div className="biz-visual"><div className="biz-orb" style={{ '--h': o.hue }} /></div>
      </div>

      {/* Services */}
      <div className="sec-head" style={{ marginTop: 44 }}>
        <h3>{isUS ? 'Build your plan' : 'What we handle'}</h3>
        <span className="meta">{isUS ? 'select per section · live estimate' : `${o.services.length} services · end to end`}</span>
      </div>
      {isUS ?
      <BizServicePicker onLead={setLead} /> :

      <div className="biz-services">
          {o.services.map((s) =>
        <div key={s.label} className="biz-service" style={{ '--h': o.hue }}>
              <div className="biz-ic">{Icon[s.icon]({})}</div>
              <div className="biz-svc-label">{s.label}</div>
              <div className="biz-svc-sub">{s.sub}</div>
            </div>
        )}
        </div>
      }

      {/* Closing CTA */}
      <div className="glass" style={{ marginTop: 36, padding: 24, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
        <div>
          <div style={{ fontFamily: 'var(--f-display)', fontStyle: 'italic', fontSize: 24 }}>Tell us what you make.</div>
          <div className="muted" style={{ fontSize: 13.5, marginTop: 2 }}>A real person reviews every application — usually within two days.</div>
        </div>
        <button className="btn btn-accent" onClick={() => setLead({ title: o.cta, interest: o.tab, kind: 'apply' })}>{o.cta} <Icon.arrow style={{ width: 14, height: 14 }} /></button>
      </div>

      {lead && <BusinessLeadForm ctx={lead} onClose={() => setLead(null)} />}
    </>);

};

window.Business = Business;
window.BizServicePicker = BizServicePicker;
