/* Shiva Corporation — Homepage prototype */
const { useState, useEffect, useRef, useMemo, useCallback } = React;

/* ─────────────────────────────────────────────  Supabase ───────── */
if (!window.supabase) throw new Error('Supabase CDN not loaded — check index.html script tags.');
if (!window.__SC_ENV)  throw new Error('config.js not loaded — check index.html script tags.');
const sb = window.supabase.createClient(window.__SC_ENV.SUPABASE_URL, window.__SC_ENV.SUPABASE_ANON_KEY);

/* ─────────────────────────────────────────────  i18n ───────── */
const T = {
  en: {
    nav: { home: "Home", products: "Products", about: "About", blog: "Blog", inquiry: "Inquiry", contact: "Contact" },
    hero_eyebrow: "Est. 1924 · Aligarh · India",
    hero_h1_a: "100+ Years",
    hero_h1_b: "Forged in",
    hero_h1_c: "Architectural",
    hero_h1_d: "Hardware",
    hero_sub: "Premium door kits & locks engineered for pan-India wholesalers, builders and contractors. Crafted with precision, durability & trust.",
    cta_explore: "Explore Products",
    cta_quote: "Get Price Quote",
    cta_inquiry: "Send Inquiry",
    badge_live: "Manufacturing · Unit 03",
    badge_sku: "FEATURED · SC-0007",
    badge_sku_label: "Double Door Kit",
    stat_years: "Years of Manufacturing",
    stat_skus: "SKUs in Catalog",
    stat_states: "States Served",
    stat_orders: "Bulk Orders Shipped",
    marquee: ["Made in India", "100+ Years Legacy", "Pan-India B2B", "Export Quality", "Certified Manufacturing", "Stainless Steel", "Door Kits & Locks"],
    products_eyebrow: "01 — Catalog",
    products_h: "Built to Last.\nMade to Specify.",
    products_lede: "Eight signature products in the active line — from heavy-duty 6-lever locks to architectural double-door kits in stainless and brass finishes.",
    filters: { all: "All Products", locks: "Locks", kits: "Door Kits", single: "Single Door", double: "Double Door" },
    search_ph: "Search SKU or product…",
    sku: "SKU",
    inquire: "Inquire",
    about_eyebrow: "02 — Legacy",
    about_h: "A Century of\nCraftsmanship.",
    about_p1: "Founded in 1924 in the brass city of **Aligarh**, Shiva Corporation has spent four generations refining a single craft — engineering architectural hardware that lasts beyond the buildings it secures.",
    about_p2: "Today we ship to **28 states**, supply over **2,400 wholesale partners**, and operate three manufacturing units running automated CNC, hand-finishing, and a quality lab that tests every batch to IS standards.",
    cta_h_a: "Need pricing on a",
    cta_h_b: "bulk order?",
    cta_call: "Call sales",
    contact_eyebrow: "03 — Reach us",
    contact_h: "Aligarh, UP\n— PAN India.",
    info: { address: "Address", email: "Email", phone: "Phone", gst: "GST", hours: "Hours" },
    map_label: "Aligarh, UP 202001",
    foot_tag: "Architectural hardware. Engineered in Aligarh since 1924.",
    foot_explore: "Explore",
    foot_company: "Company",
    foot_connect: "Connect",
    foot_newsletter: "Trade updates & new product drops, quarterly.",
    foot_subscribe: "Subscribe",
    foot_rights: "© 2026 Shiva Corporation. All rights reserved.",
    modal_eyebrow: "Send an inquiry",
    modal_h: "Get a Quote in 24 Hours.",
    modal_p_a: "Tell us what you need — our sales team will revert with bulk pricing, samples, and lead time.",
    modal_bullets: ["Quote sent to your inbox in under 24h", "Sample dispatch for orders > 100 units", "Dedicated WhatsApp line for trade customers"],
    fields: { name: "Full name", phone: "Phone number", email: "Email address", company: "Company name", city: "City / State", product: "Product interested in", sku: "Product SKU", qty: "Quantity required", msg: "Message / Requirement" },
    submit: "Send Inquiry",
    or_whatsapp: "or, WhatsApp us",
    note: "We respond within 24h on business days · No spam, ever.",
    thanks_h: "Inquiry received.",
    thanks_p: "Our sales team will contact you shortly with pricing details. We typically respond within 24 hours.",
    thanks_close: "Close",
    fab_inquiry: "Send Inquiry"
  },
  hi: {
    nav: { home: "होम", products: "उत्पाद", about: "हमारे बारे में", blog: "ब्लॉग", inquiry: "पूछताछ", contact: "संपर्क" },
    hero_eyebrow: "स्थापित 1924 · अलीगढ़ · भारत",
    hero_h1_a: "100+ वर्ष",
    hero_h1_b: "ढाले गए",
    hero_h1_c: "स्थापत्य",
    hero_h1_d: "हार्डवेयर",
    hero_sub: "अखिल भारतीय होलसेलर्स, बिल्डर्स और ठेकेदारों के लिए डिज़ाइन किए गए प्रीमियम डोर किट और लॉक। सटीकता, टिकाऊपन और भरोसे के साथ निर्मित।",
    cta_explore: "उत्पाद देखें",
    cta_quote: "कीमत प्राप्त करें",
    cta_inquiry: "पूछताछ भेजें",
    badge_live: "निर्माणाधीन · यूनिट 03",
    badge_sku: "विशेष · SC-0007",
    badge_sku_label: "डबल डोर किट",
    stat_years: "वर्षों का निर्माण",
    stat_skus: "कैटलॉग में SKU",
    stat_states: "राज्यों में सेवा",
    stat_orders: "थोक ऑर्डर पूरे",
    marquee: ["मेड इन इंडिया", "100+ वर्ष की विरासत", "अखिल भारतीय B2B", "एक्सपोर्ट क्वालिटी", "प्रमाणित निर्माण", "स्टेनलेस स्टील", "डोर किट और लॉक"],
    products_eyebrow: "01 — कैटलॉग",
    products_h: "टिकाऊ बनाया।\nविशेष रूप से बनाया।",
    products_lede: "सक्रिय लाइन में आठ हस्ताक्षर उत्पाद — हैवी-ड्यूटी 6-लीवर लॉक से लेकर स्टेनलेस और ब्रास फिनिश में आर्किटेक्चरल डबल-डोर किट तक।",
    filters: { all: "सभी उत्पाद", locks: "लॉक्स", kits: "डोर किट्स", single: "सिंगल डोर", double: "डबल डोर" },
    search_ph: "SKU या उत्पाद खोजें…",
    sku: "SKU",
    inquire: "पूछताछ",
    about_eyebrow: "02 — विरासत",
    about_h: "एक सदी की\nकारीगरी।",
    about_p1: "1924 में पीतल नगरी **अलीगढ़** में स्थापित, शिवा कॉर्पोरेशन ने चार पीढ़ियों से एक ही शिल्प को निखारा है — स्थापत्य हार्डवेयर का निर्माण जो उन इमारतों से भी अधिक टिकता है जिन्हें यह सुरक्षित करता है।",
    about_p2: "आज हम **28 राज्यों** में आपूर्ति करते हैं, **2,400+ होलसेल पार्टनर्स** की सेवा करते हैं, और तीन निर्माण इकाइयाँ चलाते हैं — स्वचालित CNC, हस्त-परिष्करण, और एक गुणवत्ता प्रयोगशाला जो हर बैच का IS मानकों पर परीक्षण करती है।",
    cta_h_a: "थोक ऑर्डर के लिए",
    cta_h_b: "कीमत चाहिए?",
    cta_call: "सेल्स को कॉल करें",
    contact_eyebrow: "03 — हमसे जुड़ें",
    contact_h: "अलीगढ़, यूपी\n— पूरे भारत में।",
    info: { address: "पता", email: "ईमेल", phone: "फोन", gst: "GST", hours: "समय" },
    map_label: "अलीगढ़, यूपी 202001",
    foot_tag: "स्थापत्य हार्डवेयर। अलीगढ़ में 1924 से निर्मित।",
    foot_explore: "अन्वेषण",
    foot_company: "कंपनी",
    foot_connect: "जुड़ें",
    foot_newsletter: "त्रैमासिक ट्रेड अपडेट और नए उत्पाद अलर्ट।",
    foot_subscribe: "सब्सक्राइब",
    foot_rights: "© 2026 शिवा कॉर्पोरेशन। सर्वाधिकार सुरक्षित।",
    modal_eyebrow: "पूछताछ भेजें",
    modal_h: "24 घंटे में कोटेशन पाएं।",
    modal_p_a: "हमें बताएं कि आपको क्या चाहिए — हमारी सेल्स टीम बल्क प्राइसिंग, सैंपल और लीड टाइम के साथ जवाब देगी।",
    modal_bullets: ["24 घंटे के अंदर इनबॉक्स में कोटेशन", "100+ यूनिट ऑर्डर पर सैंपल भेजे जाते हैं", "ट्रेड ग्राहकों के लिए डेडिकेटेड WhatsApp"],
    fields: { name: "पूरा नाम", phone: "फोन नंबर", email: "ईमेल पता", company: "कंपनी का नाम", city: "शहर / राज्य", product: "रुचि का उत्पाद", sku: "उत्पाद SKU", qty: "आवश्यक मात्रा", msg: "संदेश / आवश्यकता" },
    submit: "पूछताछ भेजें",
    or_whatsapp: "या, WhatsApp पर भेजें",
    note: "हम कारोबारी दिनों में 24 घंटे के अंदर जवाब देते हैं · कोई स्पैम नहीं।",
    thanks_h: "पूछताछ प्राप्त हुई।",
    thanks_p: "हमारी सेल्स टीम जल्द ही कीमत के विवरण के साथ आपसे संपर्क करेगी। हम आमतौर पर 24 घंटे के अंदर जवाब देते हैं।",
    thanks_close: "बंद करें",
    fab_inquiry: "पूछताछ"
  }
};

/* ─────────────────────────────────────────────  Product data ───────── */
const PRODUCTS = [
  { id: "SC-0001", name_en: "Mudiya 4 Lever", name_hi: "मुदिया 4 लीवर", cat: "locks", sub: "Single Door", desc_en: "Heavy-duty brass mechanism, satin chrome finish.", desc_hi: "हैवी-ड्यूटी ब्रास मैकेनिज़्म, सैटिन क्रोम फिनिश।", img: "https://images.unsplash.com/photo-1558618047-3c8c76ca7d13?w=900&q=70" },
  { id: "SC-0002", name_en: "00 Lock — Compact", name_hi: "00 लॉक — कॉम्पैक्ट", cat: "locks", sub: "Single Door", desc_en: "Compact 5-pin tumbler. High-volume residential build.", desc_hi: "कॉम्पैक्ट 5-पिन टम्बलर। आवासीय निर्माण के लिए।", img: "https://images.unsplash.com/photo-1614064642639-e398cf05badb?w=900&q=70" },
  { id: "SC-0003", name_en: "Mini Bhatia 6 Lever", name_hi: "मिनी भाटिया 6 लीवर", cat: "locks", sub: "Single Door", desc_en: "6-lever security, compact body. Anti-pick design.", desc_hi: "6-लीवर सिक्योरिटी, कॉम्पैक्ट बॉडी। एंटी-पिक डिज़ाइन।", img: "https://images.unsplash.com/photo-1581094277482-d3b3b1c0d6dc?w=900&q=70" },
  { id: "SC-0004", name_en: "Bhatia 6 Lever", name_hi: "भाटिया 6 लीवर", cat: "locks", sub: "Single Door", desc_en: "Flagship 6-lever lock. Hardened steel shackle.", desc_hi: "फ्लैगशिप 6-लीवर लॉक। हार्डन्ड स्टील शैकल।", img: "https://images.unsplash.com/photo-1581094289810-adf5d25690e3?w=900&q=70" },
  { id: "SC-0005", name_en: "Single Door Kit — 16×5", name_hi: "सिंगल डोर किट — 16×5", cat: "kits", sub: "Single Door", desc_en: "Complete kit: hinges, handles, lock, latch. 16×5 size.", desc_hi: "पूरा किट: हिंजेज, हैंडल, लॉक, लैच। 16×5 साइज़।", img: "https://images.unsplash.com/photo-1503387762-592deb58ef4e?w=900&q=70" },
  { id: "SC-0006", name_en: "Single Door Kit — 16×3", name_hi: "सिंगल डोर किट — 16×3", cat: "kits", sub: "Single Door", desc_en: "Compact 16×3 kit, satin finish. Residential grade.", desc_hi: "कॉम्पैक्ट 16×3 किट, सैटिन फिनिश। आवासीय ग्रेड।", img: "https://images.unsplash.com/photo-1593696140826-c58b021acf8b?w=900&q=70" },
  { id: "SC-0007", name_en: "Double Door Kit — 16×5", name_hi: "डबल डोर किट — 16×5", cat: "kits", sub: "Double Door", desc_en: "Premium double door kit, full hardware suite.", desc_hi: "प्रीमियम डबल डोर किट, पूरा हार्डवेयर सूट।", img: "https://images.unsplash.com/photo-1614064642639-e398cf05badb?w=900&q=70&sat=-30" },
  { id: "SC-0008", name_en: "Double Door Kit — 16×3", name_hi: "डबल डोर किट — 16×3", cat: "kits", sub: "Double Door", desc_en: "Architectural double door kit. 16×3, satin chrome.", desc_hi: "आर्किटेक्चरल डबल डोर किट। 16×3, सैटिन क्रोम।", img: "https://images.unsplash.com/photo-1503387762-592deb58ef4e?w=900&q=70&sat=-30" }
];

/* ─────────────────────────────────────────────  Helpers ───────── */
function useReveal() {
  useEffect(() => {
    const obs = new IntersectionObserver(
      (entries) => entries.forEach(e => e.isIntersecting && e.target.classList.add('shown')),
      { threshold: 0.12, rootMargin: "0px 0px -60px 0px" }
    );
    document.querySelectorAll('.reveal:not(.shown)').forEach(el => obs.observe(el));
    return () => obs.disconnect();
  });
}

function Counter({ to, suffix = "", duration = 1800 }) {
  const ref = useRef(null);
  const [val, setVal] = useState(0);
  const seen = useRef(false);
  useEffect(() => {
    const obs = new IntersectionObserver((ents) => {
      ents.forEach(e => {
        if (e.isIntersecting && !seen.current) {
          seen.current = true;
          const start = performance.now();
          const step = (now) => {
            const t = Math.min(1, (now - start) / duration);
            const eased = 1 - Math.pow(1 - t, 3);
            setVal(Math.round(to * eased));
            if (t < 1) requestAnimationFrame(step);
          };
          requestAnimationFrame(step);
        }
      });
    }, { threshold: 0.4 });
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, [to, duration]);
  return <span ref={ref} className="counter-num">{val.toLocaleString('en-IN')}{suffix}</span>;
}

/* ─────────────────────────────────────────────  Nav ───────── */
function Nav({ lang, setLang, onInquiry, t, active, setActive }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const links = ["home", "products", "about", "blog", "inquiry", "contact"];
  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="wrap nav-inner">
        <a className="brand" href="#home" onClick={() => setActive("home")}>
          <div className="brand-mark"></div>
          <div>
            <div className="brand-name">SHIVA CORP.</div>
            <div className="brand-sub">Est. 1924 · Aligarh</div>
          </div>
        </a>
        <div className="nav-links">
          {links.map(k => (
            <a key={k} href={`#${k}`} className={`nav-link ${active === k ? 'active' : ''}`}
              onClick={(e) => { setActive(k); if (k === "inquiry") { e.preventDefault(); onInquiry(); } }}>
              {t.nav[k]}
            </a>
          ))}
        </div>
        <div className="nav-right">
          <div className="lang-pill">
            <button className={lang === "en" ? "on" : ""} onClick={() => setLang("en")}>EN</button>
            <button className={lang === "hi" ? "on" : ""} onClick={() => setLang("hi")}>हि</button>
          </div>
          <button className="btn accent sm" onClick={onInquiry}>
            {t.cta_inquiry}
            <span className="arr">→</span>
          </button>
        </div>
      </div>
    </nav>
  );
}

/* ─────────────────────────────────────────────  Hero ───────── */
function Hero({ t, onInquiry }) {
  return (
    <section className="hero" id="home">
      <div className="hero-bg" style={{ backgroundImage: 'url(https://images.unsplash.com/photo-1581094277482-d3b3b1c0d6dc?w=1800&q=80)' }}></div>
      <div className="streaks">
        <div className="streak" style={{ top: '20%', '--rot': '-4deg', animationDelay: '0s' }}></div>
        <div className="streak" style={{ top: '46%', '--rot': '3deg', animationDelay: '0.8s' }}></div>
        <div className="streak" style={{ top: '72%', '--rot': '-2deg', animationDelay: '1.6s' }}></div>
      </div>
      <div className="wrap">
        <div className="hero-grid">
          <div>
            <div className="hero-meta reveal shown">
              <div className="mono">{t.hero_eyebrow}</div>
              <div className="hero-meta-line"></div>
              <div className="mono" style={{ color: 'var(--accent)' }}>SC · 28 STATES</div>
            </div>
            <h1>
              <span className="reveal shown">100+ Years</span><br/>
              <span className="stroke reveal shown delay-1">Forged in</span><br/>
              <span className="reveal shown delay-2">Architectural</span><br/>
              <span className="ink reveal shown delay-3">Hardware.</span>
            </h1>
            <p className="hero-sub reveal delay-4">{t.hero_sub}</p>
            <div className="hero-ctas reveal delay-4">
              <a className="btn accent" href="#products"><span>{t.cta_explore}</span><span className="arr">→</span></a>
              <button className="btn ghost" onClick={onInquiry}><span>{t.cta_quote}</span><span className="arr">→</span></button>
            </div>
          </div>
          <div className="hero-side reveal delay-2">
            <div className="hero-img" style={{ backgroundImage: 'url(https://images.unsplash.com/photo-1558618047-3c8c76ca7d13?w=1200&q=80)' }}></div>
            <div className="badge"><span className="dot"></span><span>{t.badge_live}</span></div>
            <div className="ticket">
              <div className="ticket-text">
                <div className="label">{t.badge_sku}</div>
                <div className="val">{t.badge_sku_label}</div>
              </div>
              <button className="btn sm accent" onClick={onInquiry}>
                <span>{t.cta_quote}</span>
                <span className="arr">→</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────────────────────────────  Marquee ───────── */
function Marquee({ t }) {
  const items = [...t.marquee, ...t.marquee];
  return (
    <div className="marquee">
      <div className="marquee-track">
        {items.map((s, i) => (
          <div className="marquee-item" key={i}>
            <span className="ico"></span>{s}
          </div>
        ))}
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────  Stats ───────── */
function Stats({ t }) {
  const rows = [
    { idx: "01", n: 102, suffix: "+", l: t.stat_years },
    { idx: "02", n: 48, suffix: "", l: t.stat_skus },
    { idx: "03", n: 28, suffix: "", l: t.stat_states },
    { idx: "04", n: 2400, suffix: "+", l: t.stat_orders },
  ];
  return (
    <section className="wrap" style={{ paddingTop: 80 }}>
      <div className="stats">
        {rows.map((r, i) => (
          <div className="stat reveal" key={r.idx} style={{ transitionDelay: `${i * 80}ms` }}>
            <div className="top">
              <span className="idx">{r.idx}</span>
              <span className="bar"></span>
            </div>
            <div className="n"><Counter to={r.n} suffix={r.suffix} /></div>
            <div className="l">{r.l}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ─────────────────────────────────────────────  Products ───────── */
function Products({ t, lang, onInquire }) {
  const [filter, setFilter] = useState("all");
  const [query, setQuery] = useState("");
  const filters = [
    { id: "all", label: t.filters.all },
    { id: "locks", label: t.filters.locks },
    { id: "kits", label: t.filters.kits },
    { id: "single", label: t.filters.single },
    { id: "double", label: t.filters.double },
  ];
  const filtered = useMemo(() => {
    return PRODUCTS.filter(p => {
      if (filter === "locks" && p.cat !== "locks") return false;
      if (filter === "kits" && p.cat !== "kits") return false;
      if (filter === "single" && p.sub !== "Single Door") return false;
      if (filter === "double" && p.sub !== "Double Door") return false;
      if (query) {
        const q = query.toLowerCase();
        return p.id.toLowerCase().includes(q) || p.name_en.toLowerCase().includes(q) || p.name_hi.includes(query);
      }
      return true;
    });
  }, [filter, query]);

  return (
    <section className="block" id="products">
      <div className="wrap">
        <div className="section-head reveal">
          <div>
            <div className="eyebrow"><span className="num">{t.products_eyebrow.split(' — ')[0]}</span>—<span>{t.products_eyebrow.split(' — ')[1]}</span></div>
            <h2 style={{ whiteSpace: 'pre-line' }}>{t.products_h}</h2>
          </div>
          <p className="lede">{t.products_lede}</p>
        </div>

        <div className="filters reveal">
          {filters.map(f => (
            <button key={f.id} className={`chip ${filter === f.id ? 'on' : ''}`} onClick={() => setFilter(f.id)}>
              {f.label}
            </button>
          ))}
          <div className="spacer"></div>
          <div className="search">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>
            <input placeholder={t.search_ph} value={query} onChange={e => setQuery(e.target.value)} />
          </div>
        </div>

        <div className="products">
          {filtered.map((p, idx) => (
            <div key={p.id} className="card reveal" style={{ transitionDelay: `${(idx % 4) * 60}ms` }}>
              <a className="card-link" href={`product.html?sku=${p.id}`} target="_blank" rel="noopener" style={{ display: 'block', color: 'inherit' }}>
                <div className="card-img">
                  <div className="card-sku">{p.id}</div>
                  <div className="card-cat">{p.cat === "locks" ? t.filters.locks : t.filters.kits}</div>
                  <div className="img" style={{ backgroundImage: `url(${p.img})` }}></div>
                </div>
                <div className="card-body">
                  <div className="card-title">{lang === "hi" ? p.name_hi : p.name_en}</div>
                  <div className="card-meta">{lang === "hi" ? p.desc_hi : p.desc_en}</div>
                </div>
              </a>
              <div className="card-foot">
                <div className="card-price">PRICE ON INQUIRY</div>
                <button className="card-cta" onClick={() => onInquire(p)}>{t.inquire} <span className="arr">→</span></button>
              </div>
            </div>
          ))}
        </div>
        {filtered.length === 0 && (
          <div style={{ padding: 60, textAlign: 'center', color: 'var(--fg-2)' }}>No products match.</div>
        )}
      </div>
    </section>
  );
}

/* ─────────────────────────────────────────────  About ───────── */
function About({ t }) {
  const timeline = [
    { y: "1924", t_en: "Founded in Aligarh", d_en: "First workshop, hand-forged padlocks for North India dealers.", t_hi: "अलीगढ़ में स्थापना", d_hi: "पहली वर्कशॉप, उत्तर भारत के डीलरों के लिए हस्त-निर्मित ताले।" },
    { y: "1968", t_en: "First Mechanized Unit", d_en: "Introduced precision dies, scaled to 50 districts.", t_hi: "पहली मशीनीकृत यूनिट", d_hi: "सटीक डाई पेश की, 50 जिलों तक विस्तार।" },
    { y: "1994", t_en: "Stainless Steel Line", d_en: "Launched the architectural door-kit category.", t_hi: "स्टेनलेस स्टील लाइन", d_hi: "आर्किटेक्चरल डोर-किट श्रेणी की शुरुआत।" },
    { y: "2018", t_en: "CNC Manufacturing", d_en: "Automated CNC + ISO 9001:2015 quality certification.", t_hi: "CNC निर्माण", d_hi: "स्वचालित CNC + ISO 9001:2015 गुणवत्ता प्रमाणन।" },
    { y: "2024", t_en: "Century Milestone", d_en: "Pan-India distribution. 100 years of architectural hardware.", t_hi: "शताब्दी मील का पत्थर", d_hi: "अखिल भारतीय वितरण। स्थापत्य हार्डवेयर के 100 वर्ष।" },
  ];
  // simple markdown for **bold**
  const md = (s) => s.split(/(\*\*[^*]+\*\*)/g).map((seg, i) => seg.startsWith("**") ? <strong key={i}>{seg.slice(2, -2)}</strong> : <React.Fragment key={i}>{seg}</React.Fragment>);

  return (
    <section className="block" id="about" style={{ background: 'var(--bg-2)', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
      <div className="wrap">
        <div className="about-grid">
          <div className="about-img reveal">
            <div className="img" style={{ backgroundImage: 'url(https://images.unsplash.com/photo-1581094289810-adf5d25690e3?w=1200&q=80)' }}></div>
          </div>
          <div className="about-body">
            <div className="eyebrow reveal" style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 11, letterSpacing: '0.2em', color: 'var(--fg-2)', textTransform: 'uppercase', marginBottom: 14 }}>
              <span style={{ color: 'var(--accent)' }}>{t.about_eyebrow.split(' — ')[0]}</span>—<span>{t.about_eyebrow.split(' — ')[1]}</span>
            </div>
            <h2 className="reveal" style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(36px, 4.5vw, 64px)', lineHeight: 0.92, margin: 0, textTransform: 'uppercase', whiteSpace: 'pre-line' }}>
              {t.about_h}
            </h2>
            <div className="reveal delay-1" style={{ marginTop: 28 }}>
              <p style={{ fontSize: 17, lineHeight: 1.6, color: 'var(--fg-2)', margin: '0 0 18px' }}>{md(t.about_p1)}</p>
              <p style={{ fontSize: 17, lineHeight: 1.6, color: 'var(--fg-2)', margin: 0 }}>{md(t.about_p2)}</p>
            </div>
            <div className="timeline reveal delay-2">
              {timeline.map((row) => (
                <div className="tl" key={row.y}>
                  <div className="y">{row.y}</div>
                  <div>
                    <div className="t">{row.t_en}</div>
                    <div className="d">{row.d_en}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────────────────────────────  CTA strip ───────── */
function CtaStrip({ t, onInquiry }) {
  return (
    <section className="cta-strip">
      <div className="cta-strip-bg"></div>
      <div className="wrap">
        <h3 className="reveal">
          {t.cta_h_a} <span className="ink">{t.cta_h_b}</span>
        </h3>
        <div className="ctas reveal delay-1">
          <button className="btn accent" onClick={onInquiry}>{t.cta_inquiry} <span className="arr">→</span></button>
          <a className="btn ghost" href="tel:+919760208032">{t.cta_call} <span className="arr">→</span></a>
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────────────────────────────  Contact ───────── */
function Contact({ t }) {
  return (
    <section className="block" id="contact">
      <div className="wrap">
        <div className="section-head reveal">
          <div>
            <div className="eyebrow"><span className="num">{t.contact_eyebrow.split(' — ')[0]}</span>—<span>{t.contact_eyebrow.split(' — ')[1]}</span></div>
            <h2 style={{ whiteSpace: 'pre-line' }}>{t.contact_h}</h2>
          </div>
        </div>
        <div className="contact-grid">
          <div className="contact-info">
            <div className="info-row reveal">
              <div className="l">{t.info.address}</div>
              <div className="v">Shiva Corporation<br/>Industrial Estate, Aligarh<br/>Uttar Pradesh 202001, India</div>
            </div>
            <div className="info-row reveal delay-1">
              <div className="l">{t.info.email}</div>
              <div className="v"><a href="mailto:business.shivacorp@gmail.com">business.shivacorp@gmail.com</a></div>
            </div>
            <div className="info-row reveal delay-2">
              <div className="l">{t.info.phone}</div>
              <div className="v"><a href="tel:+919760208032">+91 97602 08032</a> · <a href="https://wa.me/919760208032">WhatsApp</a></div>
            </div>
            <div className="info-row reveal delay-2">
              <div className="l">{t.info.gst}</div>
              <div className="v" style={{ fontFamily: 'var(--font-mono)', letterSpacing: '0.04em' }}>09BAKPV4457K1ZV</div>
            </div>
            <div className="info-row reveal delay-3">
              <div className="l">{t.info.hours}</div>
              <div className="v">Mon — Sat · 09:30 — 18:30 IST</div>
            </div>
          </div>
          <div className="map reveal">
            <div className="pattern"></div>
            <div className="pin"></div>
            <div className="label">{t.map_label}</div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────────────────────────────  Footer ───────── */
function Footer({ t }) {
  return (
    <footer>
      <div className="wrap">
        <div className="foot-grid">
          <div className="foot-col">
            <div className="brand" style={{ marginBottom: 16 }}>
              <div className="brand-mark"></div>
              <div>
                <div className="brand-name">SHIVA CORP.</div>
                <div className="brand-sub">Est. 1924 · Aligarh</div>
              </div>
            </div>
            <p style={{ color: 'var(--fg-2)', fontSize: 14, lineHeight: 1.55, maxWidth: 320 }}>{t.foot_tag}</p>
            <div className="foot-newsletter" style={{ marginTop: 24 }}>
              <div style={{ fontSize: 12, color: 'var(--fg-2)', marginBottom: 8 }}>{t.foot_newsletter}</div>
              <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                <input placeholder="you@company.com" />
                <button className="btn sm accent">{t.foot_subscribe}</button>
              </div>
            </div>
          </div>
          <div className="foot-col">
            <h5>{t.foot_explore}</h5>
            <ul>
              <li><a href="#products">{t.nav.products}</a></li>
              <li><a href="#about">{t.nav.about}</a></li>
              <li><a href="#contact">{t.nav.contact}</a></li>
              <li><a href="#blog">{t.nav.blog}</a></li>
            </ul>
          </div>
          <div className="foot-col">
            <h5>{t.foot_company}</h5>
            <ul>
              <li><a href="#">Legacy &amp; Story</a></li>
              <li><a href="#">Manufacturing</a></li>
              <li><a href="#">Certifications</a></li>
              <li><a href="#">Careers</a></li>
              <li><a href="admin-login.html">Admin Console</a></li>
            </ul>
          </div>
          <div className="foot-col">
            <h5>{t.foot_connect}</h5>
            <ul>
              <li><a href="#">WhatsApp</a></li>
              <li><a href="#">Instagram</a></li>
              <li><a href="#">LinkedIn</a></li>
              <li><a href="#">YouTube</a></li>
            </ul>
          </div>
        </div>
        <div className="foot-base">
          <div>{t.foot_rights}</div>
          <div className="gst">GSTIN · 09BAKPV4457K1ZV</div>
        </div>
      </div>
    </footer>
  );
}

/* ─────────────────────────────────────────────  Modal ───────── */
function InquiryModal({ open, onClose, t, prefillProduct, lang }) {
  const [form, setForm] = useState({ name: "", phone: "", email: "", company: "", city: "", product: "", qty: "", msg: "" });
  const [errors, setErrors] = useState({});
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState(null);

  useEffect(() => {
    if (open && prefillProduct) {
      const pname = lang === "hi" ? prefillProduct.name_hi : prefillProduct.name_en;
      setForm(f => ({ ...f, product: `${pname} (${prefillProduct.id})` }));
    }
  }, [open, prefillProduct, lang]);

  useEffect(() => {
    if (!open) {
      setTimeout(() => { setSubmitted(false); setErrors({}); setSubmitting(false); setSubmitError(null); }, 350);
    } else {
      document.body.style.overflow = 'hidden';
    }
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  const onChange = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const submit = (e) => {
    e.preventDefault();
    const er = {};
    if (!form.name.trim()) er.name = "Required";
    if (!form.phone.trim() || !/^[+\d\s\-]{8,}$/.test(form.phone.trim())) er.phone = "Valid phone required";
    setErrors(er);
    if (Object.keys(er).length > 0) return;

    setSubmitting(true);
    setSubmitError(null);

    const skuMatch = form.product.match(/\(([^)]+)\)$/);
    const sku = skuMatch ? skuMatch[1] : '';

    const payload = {
      id:      crypto.randomUUID(),
      name:    form.name.trim(),
      phone:   form.phone.trim(),
      email:   form.email.trim() || null,
      company: form.company.trim() || null,
      city:    form.city.trim()    || null,
      product: form.product        || null,
      sku:     sku                 || null,
      qty:     form.qty ? parseInt(form.qty, 10) : 0,
      msg:     form.msg.trim()     || null,
    };

    console.log('[inquiry] Submitting:', payload);

    sb.from('sc_inquiries')
      .insert(payload)
      .then(function(result) {
        console.log('[inquiry] Result:', result);
        if (result.error) {
          console.error('[inquiry] DB error:', result.error.message);
          setSubmitError(result.error.message);
          setSubmitting(false);
        } else {
          setSubmitting(false);
          setSubmitted(true);
        }
      })
      .catch(function(err) {
        console.error('[inquiry] Network error:', err);
        setSubmitError('Network error. Please try again.');
        setSubmitting(false);
      });
  };

  return (
    <div className={`modal-back ${open ? 'open' : ''}`} onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal-side">
          <div>
            <div className="label">{t.modal_eyebrow}</div>
            <h4>{t.modal_h}</h4>
            <p style={{ color: 'var(--fg-2)', fontSize: 14, lineHeight: 1.55, margin: '14px 0 0' }}>{t.modal_p_a}</p>
          </div>
          <ul className="ul" style={{ listStyle: 'none', padding: 0, margin: 0 }}>
            {t.modal_bullets.map((b, i) => <li key={i}>{b}</li>)}
          </ul>
        </div>
        <div className="modal-body">
          {!submitted ? (
            <>
              <div className="modal-head">
                <div>
                  <div className="mono">SC · INQUIRY FORM</div>
                  <h3>{t.modal_eyebrow}</h3>
                </div>
                <button className="modal-close" onClick={onClose}>×</button>
              </div>
              <form className="form-grid" onSubmit={submit} noValidate>
                {[
                  { k: "name",    full: false },
                  { k: "phone",   full: false, type: "tel" },
                  { k: "email",   full: false, type: "email" },
                  { k: "company", full: false },
                  { k: "city",    full: false },
                  { k: "product", full: true, select: true },
                  { k: "qty",     full: false, type: "number" },
                  { k: "msg",     full: true,  area: true },
                ].map(({ k, full, type, area, select }) => (
                  <div key={k} className={`field ${full ? 'full' : ''} ${errors[k] ? 'error' : ''} ${form[k] ? 'filled' : ''}`}>
                    {select ? (
                      <select value={form[k]} onChange={e => onChange(k, e.target.value)}>
                        <option value=""></option>
                        {PRODUCTS.map(p => (
                          <option key={p.id} value={`${lang === "hi" ? p.name_hi : p.name_en} (${p.id})`}>
                            {lang === "hi" ? p.name_hi : p.name_en} — {p.id}
                          </option>
                        ))}
                        <option value="Multiple products / General inquiry">{lang === "hi" ? "एकाधिक उत्पाद / सामान्य पूछताछ" : "Multiple products / General inquiry"}</option>
                      </select>
                    ) : area ? (
                      <textarea placeholder=" " value={form[k]} onChange={e => onChange(k, e.target.value)} rows="3" />
                    ) : (
                      <input type={type || "text"} placeholder=" " value={form[k]} onChange={e => onChange(k, e.target.value)} />
                    )}
                    <label>{t.fields[k]}</label>
                    {errors[k] && <div className="field-err">{errors[k]}</div>}
                  </div>
                ))}
                <div className="form-actions full" style={{ gridColumn: '1/-1' }}>
                  <span className="form-note">{t.note}</span>
                  <div style={{ display: 'flex', gap: 10 }}>
                    <a className="btn ghost sm" href="https://wa.me/919760208032" target="_blank" rel="noreferrer">
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M17.5 14.4c-.3-.1-1.7-.8-1.9-.9-.3-.1-.5-.1-.7.1s-.8.9-1 1.1c-.2.2-.4.2-.6.1-.3-.1-1.2-.4-2.3-1.4-.9-.8-1.4-1.7-1.6-2-.2-.3 0-.5.1-.6.1-.1.3-.3.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5 0-.1-.7-1.7-.9-2.3-.2-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1.1 1-1.1 2.4 0 1.4 1.1 2.8 1.2 3 .1.2 2.1 3.4 5.2 4.6 2.6 1 3.2.8 3.7.7.5-.1 1.7-.7 1.9-1.4.2-.7.2-1.2.2-1.4 0-.1-.2-.2-.5-.4z"/><path d="M12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.5 1.3 5L2 22l5.1-1.3c1.5.8 3.2 1.3 4.9 1.3 5.5 0 10-4.5 10-10S17.5 2 12 2zm0 18c-1.6 0-3.2-.4-4.5-1.2l-.3-.2-3 .8.8-2.9-.2-.3C3.9 14.9 3.5 13.5 3.5 12 3.5 7.3 7.3 3.5 12 3.5S20.5 7.3 20.5 12 16.7 20 12 20z"/></svg>
                      WhatsApp
                    </a>
                    <button type="submit" className="btn accent" disabled={submitting}>{submitting ? 'Sending…' : t.submit} <span className="arr">→</span></button>
                  </div>
                  {submitError && (
                    <div style={{ color: '#ff7878', fontSize: 12, marginTop: 8, padding: '8px 12px', background: 'rgba(255,68,68,0.08)', borderRadius: 8, border: '1px solid rgba(255,68,68,0.2)' }}>
                      ⚠ {submitError}
                    </div>
                  )}
                </div>
              </form>
            </>
          ) : (
            <div className="form-success">
              <div className="modal-head" style={{ width: '100%' }}>
                <div></div>
                <button className="modal-close" onClick={onClose}>×</button>
              </div>
              <div className="ring">
                <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                  <polyline points="20 6 9 17 4 12"/>
                </svg>
              </div>
              <h4>{t.thanks_h}</h4>
              <p>{t.thanks_p}</p>
              <button className="btn ghost" onClick={onClose}>{t.thanks_close}</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────  Floating ───────── */
function FloatingFab({ t, onInquiry }) {
  return (
    <div className="fab-stack">
      <a className="fab whats" href="https://wa.me/919760208032" target="_blank" rel="noreferrer" aria-label="WhatsApp">
        <svg width="17" height="17" viewBox="0 0 24 24" fill="currentColor"><path d="M17.5 14.4c-.3-.1-1.7-.8-1.9-.9-.3-.1-.5-.1-.7.1s-.8.9-1 1.1c-.2.2-.4.2-.6.1-.3-.1-1.2-.4-2.3-1.4-.9-.8-1.4-1.7-1.6-2-.2-.3 0-.5.1-.6.1-.1.3-.3.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5 0-.1-.7-1.7-.9-2.3-.2-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1.1 1-1.1 2.4 0 1.4 1.1 2.8 1.2 3 .1.2 2.1 3.4 5.2 4.6 2.6 1 3.2.8 3.7.7.5-.1 1.7-.7 1.9-1.4.2-.7.2-1.2.2-1.4 0-.1-.2-.2-.5-.4z"/><path d="M12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.5 1.3 5L2 22l5.1-1.3c1.5.8 3.2 1.3 4.9 1.3 5.5 0 10-4.5 10-10S17.5 2 12 2zm0 18c-1.6 0-3.2-.4-4.5-1.2l-.3-.2-3 .8.8-2.9-.2-.3C3.9 14.9 3.5 13.5 3.5 12 3.5 7.3 7.3 3.5 12 3.5S20.5 7.3 20.5 12 16.7 20 12 20z"/></svg>
      </a>
      <a className="fab call" href="tel:+919760208032" aria-label="Call">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13 1.05.37 2.07.7 3.06a2 2 0 0 1-.45 2.11L8.09 10.91a16 16 0 0 0 6 6l2.02-1.27a2 2 0 0 1 2.11-.45c.99.33 2.01.57 3.06.7A2 2 0 0 1 22 16.92z"/></svg>
      </a>
      <button className="fab inquiry" onClick={onInquiry}>
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M5 12h14m-6-6 6 6-6 6"/></svg>
        {t.fab_inquiry}
      </button>
    </div>
  );
}

/* ─────────────────────────────────────────────  Tweaks ───────── */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "dark",
  "accent": "#ff6a1f",
  "density": "comfortable",
  "cards": "flat",
  "fonts": "industrial",
  "hero": "split"
}/*EDITMODE-END*/;

function ShivaTweaks({ tweaks, setTweak }) {
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Appearance" />
      <TweakRadio label="Theme" value={tweaks.theme} options={["dark", "light"]} onChange={(v) => setTweak('theme', v)} />
      <TweakColor label="Accent" value={tweaks.accent}
        options={['#ff6a1f', '#d62828', '#f4a300', '#2a6fdb']}
        onChange={(v) => setTweak('accent', v)} />
      <TweakSection label="Layout" />
      <TweakSelect label="Hero variant" value={tweaks.hero}
        options={[
          { value: "split", label: "Split — text + side ticket" },
          { value: "fullbleed", label: "Full-bleed — cinematic image" },
          { value: "center", label: "Centered — text only" }
        ]} onChange={(v) => setTweak('hero', v)} />
      <TweakRadio label="Card style" value={tweaks.cards} options={["flat", "glass", "bordered"]} onChange={(v) => setTweak('cards', v)} />
      <TweakRadio label="Density" value={tweaks.density} options={["comfortable", "compact"]} onChange={(v) => setTweak('density', v)} />
      <TweakSection label="Typography" />
      <TweakSelect label="Pairing" value={tweaks.fonts}
        options={[
          { value: "industrial", label: "Industrial — Archivo Black" },
          { value: "editorial", label: "Editorial — Bebas Neue" },
          { value: "modern", label: "Modern — Space Grotesk" }
        ]} onChange={(v) => setTweak('fonts', v)} />
    </TweaksPanel>
  );
}

/* ─────────────────────────────────────────────  App ───────── */
function App() {
  const [lang, setLang] = useState("en");
  const [modal, setModal] = useState(false);
  const [prefill, setPrefill] = useState(null);
  const [active, setActive] = useState("home");
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const t = T[lang];

  useReveal();

  // Apply theme attrs on root + accent var
  useEffect(() => {
    document.body.dataset.theme = tweaks.theme;
    document.body.dataset.density = tweaks.density;
    document.body.dataset.cards = tweaks.cards;
    document.body.dataset.fonts = tweaks.fonts;
    document.body.dataset.hero = tweaks.hero;
    document.body.dataset.lang = lang;
    document.documentElement.style.setProperty('--accent', tweaks.accent);
    // light-mode ink switch
    document.documentElement.style.setProperty('--accent-ink', tweaks.theme === 'light' ? '#fff' : '#0a0a0a');
  }, [tweaks, lang]);

  const openInquiry = (p) => { setPrefill(p || null); setModal(true); };
  const closeInquiry = () => setModal(false);

  // Track scroll for active section
  useEffect(() => {
    const sections = ["home", "products", "about", "contact"];
    const onScroll = () => {
      const y = window.scrollY + 120;
      for (let i = sections.length - 1; i >= 0; i--) {
        const el = document.getElementById(sections[i]);
        if (el && el.offsetTop <= y) { setActive(sections[i]); break; }
      }
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <>
      <Nav lang={lang} setLang={setLang} t={t} onInquiry={() => openInquiry()} active={active} setActive={setActive} />
      <Hero t={t} onInquiry={() => openInquiry()} />
      <Marquee t={t} />
      <Stats t={t} />
      <Products t={t} lang={lang} onInquire={(p) => openInquiry(p)} />
      <About t={t} />
      <CtaStrip t={t} onInquiry={() => openInquiry()} />
      <Contact t={t} />
      <Footer t={t} />
      <FloatingFab t={t} onInquiry={() => openInquiry()} />
      <InquiryModal open={modal} onClose={closeInquiry} t={t} prefillProduct={prefill} lang={lang} />
      <ShivaTweaks tweaks={tweaks} setTweak={setTweak} />
    </>
  );
}

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