// Services & Pricing page — 4-tab structure
// Tabs: Individual (Pay-as-you-go) · Business · Enterprise · White Label
// Below tabs: Data sources, Legal callout, FAQ

const Pricing = ({ t, lang, setPage, setPreselectedServices }) => {
  const [tab, setTab] = React.useState("individual");
  const [openFaq, setOpenFaq] = React.useState(0);
  const [picks, setPicks] = React.useState([]);

  return (
    <div>
      <div className="page-header">
        <div className="container">
          <div className="eyebrow">{t.pricing.eyebrow}</div>
          <h1 className="t-h1">{t.pricing.h1}</h1>
          <p className="sub">{t.pricing.sub}</p>
        </div>
      </div>

      {/* Beta-trust badge */}
      <section className="beta-band">
        <div className="container">
          <div className="beta-badge">
            <span className="beta-rocket">🚀</span>
            <div>
              <div className="beta-h">{lang === "ar" ? "إصدار تجريبي · أول 1,000 عميل" : "Beta launch · first 1,000 customers"}</div>
              <div className="beta-d">
                {lang === "ar"
                  ? "خصم إضافي 20% على أول 3 تقارير · وصول مبكر للميزات الجديدة · تأثير مباشر على تطوير المنصة"
                  : "Extra 20% off your first 3 reports · early access to new features · direct influence on the product"}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Tab toggle */}
      <section style={{ padding: "32px 0 0", borderBottom: "1px solid var(--hairline)" }}>
        <div className="container">
          <div className="ptabs">
            {[
              { k: "individual",   l: t.pricing.tabs.individual },
              { k: "business",     l: t.pricing.tabs.business },
              { k: "enterprise",   l: t.pricing.tabs.enterprise },
              { k: "whitelabel",   l: t.pricing.tabs.whitelabel },
            ].map(x => (
              <button
                key={x.k}
                className={"ptab" + (tab === x.k ? " on" : "")}
                onClick={() => setTab(x.k)}
                type="button"
              >{x.l}</button>
            ))}
          </div>
        </div>
      </section>

      {/* Tab content */}
      <section className="section" style={{ paddingTop: 48, paddingBottom: 64 }}>
        <div className="container">
          <div className="section-eyebrow">{t.pricing.tab_eyebrow[tab]}</div>
          <h2 className="t-h1 section-h2" style={{ marginTop: 16 }}>{t.pricing.tab_h[tab]}</h2>
          <p style={{ color: "var(--ink-500)", maxWidth: 720, marginTop: 16, fontSize: 16, lineHeight: 1.6 }}>{t.pricing.tab_sub[tab]}</p>

          {tab === "individual"  && <IndividualTab    t={t} lang={lang} picks={picks} setPicks={setPicks} setPage={setPage} setPreselectedServices={setPreselectedServices}/>}
          {tab === "business"    && <BusinessTab      t={t} lang={lang} setPage={setPage}/>}
          {tab === "enterprise"  && <EnterpriseTab    t={t} lang={lang} setPage={setPage}/>}
          {tab === "whitelabel"  && <WhiteLabelTab    t={t} lang={lang} setPage={setPage}/>}
        </div>
      </section>

      {/* Data sources (transparency) */}
      <section className="section data-sources" style={{ paddingTop: 48, background: "var(--paper-2)", borderTop: "1px solid var(--hairline)" }}>
        <div className="container">
          <div className="section-eyebrow">{lang === "ar" ? "مصادر البيانات" : "Data sources"}</div>
          <h2 className="t-h2 section-h2" style={{ marginTop: 16 }}>{lang === "ar" ? "شفافية كاملة. مصادر مفتوحة." : "Full transparency. Open public sources."}</h2>
          <p style={{ color: "var(--ink-500)", maxWidth: 720, marginTop: 16, fontSize: 16 }}>
            {lang === "ar"
              ? "كل تقرير يستند إلى البيانات الحكومية المفتوحة. دؤوب جهة مستقلة لا تُمثّل مراجعة رسمية من أي جهة، ولا تستخدم بيانات سرية."
              : "Every report draws on public open-data sources. Daoob is an independent provider — reports are not an official review by any government entity, and no confidential data is used."}
          </p>
          <div className="ds-grid">
            {[
              { icon: "📊", t: lang === "ar" ? "منصة سهيل" : "Suhail platform",       d: lang === "ar" ? "بيانات قطع الأراضي، الصفقات الموثقة، مؤشرات الأسعار" : "Parcel data, recorded transactions, price indices" },
              { icon: "🏛", t: lang === "ar" ? "منصة بلدي" : "Balady platform",        d: lang === "ar" ? "الاشتراطات التنظيمية، رخص البناء العامة، تصنيف الاستخدامات" : "Building regulations, public permits, land-use classifications" },
              { icon: "🏗", t: lang === "ar" ? "الهيئة الملكية للرياض" : "Royal Commission for Riyadh", d: lang === "ar" ? "اشتراطات الأبراج، كود وادي حنيفة، مناطق التطوير الخاصة" : "High-rise standards, Wadi Hanifa code, special development zones" },
              { icon: "📋", t: lang === "ar" ? "الهيئة العامة للعقار" : "General Real-Estate Authority", d: lang === "ar" ? "مؤشرات الإيجارات، الفهرس العقاري الوطني" : "Rent indices, National Real-Estate Index" },
              { icon: "🗺", t: lang === "ar" ? "العنوان الوطني" : "National Address",  d: lang === "ar" ? "الإحداثيات الجغرافية الدقيقة" : "Precise geographic coordinates" },
              { icon: "⚖️", t: lang === "ar" ? "وزارة الشؤون البلدية" : "Ministry of Municipal Affairs", d: lang === "ar" ? "اللوائح والاشتراطات المنشورة" : "Published regulations and standards" },
            ].map((src, i) => (
              <div key={i} className="ds-card">
                <div className="ds-icon">{src.icon}</div>
                <div className="ds-t">{src.t}</div>
                <div className="ds-d">{src.d}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Legal callout */}
      <section className="section" style={{ paddingTop: 0 }}>
        <div className="container">
          <div className="legal-callout">
            <div className="lc-icon"><Icon name="shield" size={22}/></div>
            <div>
              <div className="lc-h">{lang === "ar" ? "ملاحظة قانونية مهمة" : "Important legal notice"}</div>
              <p className="lc-p">
                {lang === "ar"
                  ? "تقارير دؤوب — بما فيها تقدير قيمة الأرض — هي تقارير استرشادية مبنية على بيانات مفتوحة وذكاء اصطناعي. لا تُعد بديلاً عن التقييم العقاري الرسمي الصادر من مقيّم معتمد لدى الهيئة السعودية للمقيّمين المعتمدين (تقييم). للتقييم المطلوب للبنوك والمحاكم، يُرجى التعاقد مع مقيّم معتمد. القرار الاستثماري النهائي يبقى مسؤولية المستثمر."
                  : "Daoob reports — including indicative land valuations — are advisory products built on open data and AI. They are not a substitute for an official real-estate appraisal issued by a valuer certified by the Saudi Authority for Accredited Valuers (Taqeem). For valuations required by banks or courts, please engage a certified valuer. The final investment decision remains the investor's responsibility."}
              </p>
              <p className="lc-p" style={{ marginTop: 6, color: "var(--gold-700)" }}>
                {lang === "ar"
                  ? "🚀 دؤوب في مرحلة الحصول على رخصة المقيّم العقاري — تابعونا للتطورات."
                  : "🚀 Daoob is in the process of obtaining a real-estate valuer licence — stay tuned for updates."}
              </p>
            </div>
          </div>
        </div>
      </section>

      {/* FAQ */}
      <section className="section">
        <div className="container">
          <div className="faq" style={{ marginTop: 0 }}>
            <div className="section-eyebrow">{t.pricing.faq_h}</div>
            <h2 className="t-h2 section-h2" style={{ marginBottom: 32 }}>{lang === "ar" ? "أسئلة العملاء الشائعة." : "What clients ask us."}</h2>
            {t.pricing.faqs.map((f, i) => (
              <div key={i} className={"faq-item" + (openFaq !== i ? " collapsed" : "")} onClick={() => setOpenFaq(openFaq === i ? -1 : i)}>
                <div className="q">
                  <span>{f.q}</span>
                  <span style={{ color: "var(--gold-600)", transform: openFaq === i ? "rotate(45deg)" : "none", transition: "transform 0.15s" }}>
                    <Icon name="plus" size={18}/>
                  </span>
                </div>
                <div className="a">{f.a}</div>
              </div>
            ))}
          </div>
        </div>
      </section>
    </div>
  );
};

Object.assign(window, { Pricing });

// ============================ INDIVIDUAL TAB ============================
const IndividualTab = ({ t, lang, picks, setPicks, setPage, setPreselectedServices }) => {
  const onPick = (idx) => {
    setPreselectedServices([]);
    setPage("request");
  };
  return (
    <>
      {/* Fixed bundles */}
      <div className="bundle-grid bundle-grid-3">
        {t.pricing.individual_bundles.map((b, i) => (
          <div key={i} className={"bundle" + (b.featured ? " featured" : "")}>
            {b.featured && <span className="badge">{lang === "ar" ? "الأكثر اختياراً" : "Most popular"}</span>}
            <div className="bundle-head">
              <div className="bundle-name">{b.name}</div>
              <div className="bundle-tag">{b.tagline}</div>
            </div>
            <div className="bundle-price">
              <span className="bp-v">{b.price}</span>
              <span className="bp-c">{b.currency}</span>
            </div>
            <div className="bundle-quota">{b.quota}</div>
            <ul className="bundle-feats">
              {b.feats.map((f, j) => <li key={j}><Icon name="check" size={11} stroke={2.5}/> {f}</li>)}
            </ul>
            <button
              className={"btn " + (b.featured ? "btn-gold" : "btn-outline")}
              onClick={() => onPick(i)}
            >{b.cta} <Icon name="arrow-right" size={14}/></button>
          </div>
        ))}
      </div>

      {/* 16-study showcase — static, non-selectable */}
      <div style={{ marginTop: 72, paddingTop: 56, borderTop: "1px solid var(--hairline)" }}>
        <div className="section-eyebrow">{lang === "ar" ? "ما يشمله كل تقرير" : "What every report covers"}</div>
        <h3 className="t-h2 section-h2" style={{ marginTop: 12 }}>{lang === "ar" ? "الدراسات الستّ عشرة." : "The 16 studies."}</h3>
        <p style={{ color: "var(--ink-500)", maxWidth: 720, marginTop: 12, fontSize: 16 }}>
          {lang === "ar"
            ? "كل تقرير يُعدّ على قالب دؤوب المعتمد، يُولّده وكلاء ذكاء متخصصون، ويُسلَّم خلال دقائق بصيغة PDF ثنائية اللغة."
            : "Every report is produced on Daoob's certified template, generated by specialized AI agents, and delivered within minutes as a bilingual PDF."}
        </p>

        <div className="studies-showcase">
          {t.services.list.map((s, i) => (
            <div key={i} className="ss-card">
              <div className="ss-num">{String(i + 1).padStart(2, "0")}</div>
              <div className="ss-title">{s.t}</div>
              <div className="ss-desc">{s.d}</div>
              {s.indicative && (
                <div className="ss-tag">
                  <Icon name="shield" size={9}/>
                  {lang === "ar" ? "استرشادي" : "Indicative"}
                </div>
              )}
            </div>
          ))}
        </div>
      </div>
    </>
  );
};

// ============================ Package builder (used inside Individual tab) ============================
const PackageBuilder = ({ t, lang, picks, setPicks, setPage, setPreselectedServices }) => {
  const toggle = (i) => setPicks(p => p.includes(i) ? p.filter(x => x !== i) : [...p, i]);
  const selectAll = () => setPicks(t.services.list.map((_, i) => i));
  const clearAll = () => setPicks([]);

  const unitPriceForCount = (n) => {
    if (n >= 16) return 250;
    if (n >= 13) return 280;
    if (n >= 10) return 300;
    if (n >= 7)  return 350;
    if (n >= 4)  return 400;
    if (n >= 2)  return 450;
    return 500;
  };
  const discountPctForCount = (n) => Math.round((1 - unitPriceForCount(n) / 500) * 100);
  const cur = lang === "ar" ? "ر.س" : "SAR";
  const unit = unitPriceForCount(picks.length);
  const total = picks.length * unit;
  const officeTotal = picks.reduce((acc, i) => {
    const m = t.services.list[i].price.match(/[\d,]+/);
    return acc + (m ? parseInt(m[0].replace(/,/g, ""), 10) : 0);
  }, 0);
  const officeSavings = officeTotal - total;
  const showUpsell = picks.length >= 8 && picks.length < 16;
  const upgradeBonus = (16 * 250) - total;

  const discountTiers = [
    { n: 1,  u: 500, pct: 0 },
    { n: 2,  u: 450, pct: 10 },
    { n: 4,  u: 400, pct: 20 },
    { n: 7,  u: 350, pct: 30 },
    { n: 10, u: 300, pct: 40 },
    { n: 13, u: 280, pct: 44 },
    { n: 16, u: 250, pct: 50 },
  ];
  const activeTierIdx = discountTiers.findIndex((tier, i) => {
    const next = discountTiers[i + 1];
    return picks.length >= tier.n && (!next || picks.length < next.n);
  });

  const goToCheckout = () => {
    if (picks.length === 0) return;
    setPreselectedServices(picks);
    setPage("request");
  };

  return (
    <>
      <div className="discount-ladder">
        <div className="dl-h">{lang === "ar" ? "السعر يقل كلما أضفت دراسات" : "The more studies you add, the lower the price"}</div>
        <div className="dl-bar">
          {discountTiers.map((tier, i) => (
            <div key={i} className={"dl-tier" + (i === activeTierIdx ? " on" : "") + (picks.length >= tier.n ? " passed" : "")}>
              <div className="dl-tier-n">{tier.n === 16 ? (lang === "ar" ? "الكل" : "All") : tier.n}+</div>
              <div className="dl-tier-u">{tier.u} <small>{cur}</small></div>
              {tier.pct > 0 && <div className="dl-tier-pct">−{tier.pct}%</div>}
            </div>
          ))}
        </div>
      </div>

      <div className="builder">
        <div className="builder-main">
          <div className="builder-toolbar">
            <h3 style={{ margin: 0, fontFamily: "var(--font-serif)", fontSize: 22, fontWeight: 400 }}>
              {t.pricing.onetime_pick} <small style={{ fontSize: 14, color: "var(--ink-400)", fontFamily: "var(--font-mono)" }}>· {t.services.list.length} {lang === "ar" ? "دراسة" : "studies"}</small>
            </h3>
            <div style={{ display: "flex", gap: 8 }}>
              <button className="btn btn-ghost btn-sm" onClick={selectAll}>{lang === "ar" ? "اختر الكل" : "Select all"}</button>
              <button className="btn btn-ghost btn-sm" onClick={clearAll} disabled={!picks.length} style={!picks.length ? { opacity: 0.4, pointerEvents: "none" } : {}}>{t.pricing.onetime_clear}</button>
            </div>
          </div>

          <div className="builder-grid">
            {t.services.list.map((s, i) => {
              const on = picks.includes(i);
              return (
                <button
                  key={i}
                  className={"build-card" + (on ? " on" : "")}
                  onClick={() => toggle(i)}
                  type="button"
                >
                  <div className="bc-head">
                    <span className="bc-num">{String(i + 1).padStart(2, "0")}</span>
                    {s.isNew && <span className="bc-newchip">{lang === "ar" ? "جديد" : "NEW"}</span>}
                    <span className="bc-check">{on && <Icon name="check" size={12} stroke={2.5}/>}</span>
                  </div>
                  <div className="bc-title">{s.t}</div>
                  <div className="bc-desc">{s.d}</div>
                  <div className="bc-prices">
                    <span className="bc-ai">{(s.daoob || 500).toLocaleString()} <small>{cur}</small></span>
                    <span className="bc-office">{s.price}</span>
                  </div>
                  {s.indicative && (
                    <div className="bc-indicative">
                      <Icon name="shield" size={10}/>
                      {lang === "ar" ? "استرشادي" : "Indicative"}
                    </div>
                  )}
                </button>
              );
            })}
          </div>
        </div>

        <aside className="builder-aside">
          <div className="builder-sum">
            <div className="bs-head">{t.pricing.onetime_summary}</div>
            {picks.length === 0 ? (
              <div className="bs-empty">
                <Icon name="file" size={32} stroke={1.2}/>
                <p>{t.pricing.onetime_empty}</p>
              </div>
            ) : (
              <>
                <div className="bs-counter">
                  <span className="bs-counter-n">{picks.length}</span>
                  <span className="bs-counter-l">
                    {lang === "ar" ? "دراسة مختارة" : (picks.length === 1 ? "study selected" : "studies selected")}
                  </span>
                </div>
                <div className="bs-line">
                  <span>{lang === "ar" ? "السعر لكل دراسة" : "Price per study"}</span>
                  <span className="bs-line-v">{unit} {cur}</span>
                </div>
                {discountPctForCount(picks.length) > 0 && (
                  <div className="bs-line bs-line-discount">
                    <span>{lang === "ar" ? "خصم الحجم" : "Volume discount"}</span>
                    <span className="bs-line-v">−{discountPctForCount(picks.length)}%</span>
                  </div>
                )}
                <div className="bs-line">
                  <span>{lang === "ar" ? "مدة الإنجاز" : "Delivery"}</span>
                  <span className="bs-line-v">{t.services.compare.ai_lead}</span>
                </div>
                {officeSavings > 0 && (
                  <div className="bs-savings">
                    <span className="bs-sav-l">{t.pricing.onetime_compare}</span>
                    <span className="bs-sav-strike">{officeTotal.toLocaleString()} {cur}</span>
                    <span className="bs-sav-v">{lang === "ar" ? "وفر" : "save"} {officeSavings.toLocaleString()} {cur}</span>
                  </div>
                )}
                {showUpsell && (
                  <button className="bs-upsell" onClick={selectAll} type="button">
                    <Icon name="plus" size={14}/>
                    {lang === "ar"
                      ? `أضف ${16 - picks.length} دراسات لجميع الـ16 — مقابل ${upgradeBonus.toLocaleString()} ${cur} فقط`
                      : `Add ${16 - picks.length} more for the full 16 — only ${upgradeBonus.toLocaleString()} ${cur} extra`}
                  </button>
                )}
              </>
            )}
            <div className="bs-total">
              <span>{t.pricing.onetime_total}</span>
              <span className="bs-total-v">{total.toLocaleString()} <small>{cur}</small></span>
            </div>
            <button
              className="btn btn-primary"
              style={{ width: "100%", justifyContent: "center", padding: "14px" }}
              onClick={goToCheckout}
              disabled={picks.length === 0}
            >
              {t.pricing.onetime_cta} <Icon name="arrow-right" size={14}/>
            </button>
            <p className="bs-fine">{lang === "ar" ? "ادفع مرة واحدة · تسليم خلال دقائق · بدون اشتراك" : "Pay once · delivered in minutes · no subscription"}</p>
          </div>
        </aside>
      </div>
    </>
  );
};

// ============================ BUSINESS TAB ============================
const BusinessTab = ({ t, lang, setPage }) => (
  <div className="biz-grid">
    {t.pricing.business_tiers.map((tier, i) => (
      <div key={i} className={"biz-tier" + (tier.featured ? " featured" : "")}>
        {tier.featured && <span className="badge">{lang === "ar" ? "الأكثر اختياراً" : "Most chosen"}</span>}
        <div className="bt-head">
          <div className="bt-name">{tier.name}</div>
          <div className="bt-tag">{tier.tagline}</div>
        </div>
        <div className="bt-quota">{tier.quota}</div>
        <div className="bt-price-row">
          <span className="bt-price">{tier.price}</span>
          <span className="bt-cur">{tier.currency}</span>
          <span className="bt-per">{tier.per}</span>
        </div>
        <div className="bt-annual">{tier.annual_note}</div>
        <div className="bt-desc">{tier.desc}</div>
        <ul className="bt-feats">
          {tier.features.map((f, j) => <li key={j}><Icon name="check" size={11} stroke={2.5}/> {f}</li>)}
        </ul>
        <button
          className={"btn " + (tier.featured ? "btn-gold" : "btn-outline")}
          onClick={() => setPage(tier.featured ? "contact" : "request")}
        >{tier.cta} <Icon name="arrow-right" size={14}/></button>
      </div>
    ))}
  </div>
);

// ============================ ENTERPRISE TAB ============================
const EnterpriseTab = ({ t, lang, setPage }) => (
  <div className="ent-grid">
    {t.pricing.enterprise_tiers.map((tier, i) => (
      <div key={i} className={"ent-tier" + (tier.featured ? " featured" : "")}>
        {tier.featured && <span className="badge">{lang === "ar" ? "الأكثر اختياراً" : "Most chosen"}</span>}
        <div className="ent-head">
          <div className="ent-name">{tier.name}</div>
          <div className="ent-tag">{tier.tagline}</div>
        </div>
        <div className="ent-quota">{tier.quota}</div>
        <div className="ent-prices">
          <div><span className="ent-k">{lang === "ar" ? "إعداد" : "Setup"}</span><span className="ent-v">{tier.setup} {lang === "ar" ? "ر.س" : "SAR"}</span></div>
          <div><span className="ent-k">{lang === "ar" ? "سنوياً" : "Annual"}</span><span className="ent-v big">{tier.annual} <small>{lang === "ar" ? "ر.س" : "SAR"}</small></span></div>
        </div>
        <ul className="ent-feats">
          {tier.feats.map((f, j) => <li key={j}><Icon name="check" size={11} stroke={2.5}/> {f}</li>)}
        </ul>
        <button
          className={"btn " + (tier.featured ? "btn-gold" : "btn-outline")}
          onClick={() => setPage("contact")}
        >{t.pricing.enterprise_cta} <Icon name="arrow-right" size={14}/></button>
      </div>
    ))}
  </div>
);

// ============================ WHITE LABEL TAB ============================
const WhiteLabelTab = ({ t, lang, setPage }) => (
  <div className="ent-grid">
    {t.pricing.whitelabel_tiers.map((tier, i) => (
      <div key={i} className={"ent-tier" + (tier.featured ? " featured" : "")}>
        {tier.featured && <span className="badge">{lang === "ar" ? "الأكثر اختياراً" : "Most chosen"}</span>}
        <div className="ent-head">
          <div className="ent-name">{tier.name}</div>
          <div className="ent-tag">{tier.tagline}</div>
        </div>
        <div className="ent-quota">{tier.quota}</div>
        <div className="ent-prices">
          <div><span className="ent-k">{lang === "ar" ? "إعداد" : "Setup"}</span><span className="ent-v">{tier.setup} {lang === "ar" ? "ر.س" : "SAR"}</span></div>
          <div><span className="ent-k">{lang === "ar" ? "سنوياً" : "Annual"}</span><span className="ent-v big">{tier.annual} <small>{lang === "ar" ? "ر.س" : "SAR"}</small></span></div>
        </div>
        <ul className="ent-feats">
          {tier.feats.map((f, j) => <li key={j}><Icon name="check" size={11} stroke={2.5}/> {f}</li>)}
        </ul>
        <button
          className={"btn " + (tier.featured ? "btn-gold" : "btn-outline")}
          onClick={() => setPage("contact")}
        >{t.pricing.whitelabel_cta} <Icon name="arrow-right" size={14}/></button>
      </div>
    ))}
  </div>
);
