/* global React, ReactDOM, TweaksPanel, TweakSection, TweakColor, TweakRadio, TweakText, TweakToggle, useTweaks */
const { useRef, useEffect } = React;

const DATA = {
  phone1: "+91 97404 22863",
  phone2: "+91 99801 11468",
  email: "vtechbuildingsystems@gmail.com",
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "brandColor": "#0e4b8c",
  "accentColor": "#e85a1a",
  "heroVariant": "Quote",
  "headline": "Premium *uPVC Windows* & Doors **for Indian homes that last**",
  "formHeadline": "Book Free Site Consultation",
  "formSub": "Our expert will visit, measure & quote — all free.",
  "offerLine": "✨ Limited: ₹0 site visit + Free design preview",
  "ctaLabel": "Submit Details",
  "showFinishes": true,
  "showGallery": true,
  "showClients": true,
  "showReviews": true
}/*EDITMODE-END*/;

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const leadFormRef = useRef(null);

  // Apply color tweaks live as CSS variables
  useEffect(() => {
    const root = document.documentElement;
    root.style.setProperty('--brand', t.brandColor);
    root.style.setProperty('--brand-ink', shade(t.brandColor, -0.35));
    root.style.setProperty('--brand-soft', shade(t.brandColor, 0.15));
    root.style.setProperty('--accent', t.accentColor);
    root.style.setProperty('--accent-deep', shade(t.accentColor, -0.2));
    root.style.setProperty('--accent-soft', tint(t.accentColor, 0.85));
  }, [t.brandColor, t.accentColor]);

  const scrollToForm = () => leadFormRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });

  const variantCopy = {
    Quote: {
      headline: t.headline,
      formHeadline: t.formHeadline,
      formSub: t.formSub,
      offer: t.offerLine,
      cta: t.ctaLabel,
    },
    Discount: {
      headline: "**Save up to ₹40,000** on Premium *uPVC Windows*",
      formHeadline: "Claim Your Monsoon Discount",
      formSub: "Limited-period offer for Bangalore homes. Book before stock runs out.",
      offer: "🎉 Up to 15% off + Free German hardware upgrade",
      cta: "Claim Discount",
    },
    Visit: {
      headline: "*Free Site Visit* by India's **#1 uPVC Window Brand**",
      formHeadline: "Schedule Your Free Visit",
      formSub: "An expert visits at your convenience. No pushy sales — just honest advice.",
      offer: "📅 Same-day visit available • Mon to Sun",
      cta: "Book Free Visit",
    },
  };
  const copy = variantCopy[t.heroVariant] || variantCopy.Quote;

  const formProps = {
    headline: copy.formHeadline,
    sub: copy.formSub,
    offer: copy.offer,
    ctaLabel: copy.cta,
    onSubmit: (data) => {
      console.log("lead submitted", data);
      
      // Save details in sessionStorage for the personalized thank-you page
      try {
        sessionStorage.setItem("vtech_lead", JSON.stringify({ name: data.first, phone: data.phone }));
      } catch (_) {}

      const goThanks = () => {
        window.location.href = "thank-you.html";
      };

      // Submit lead securely via SMTP & CSV Catcher
      fetch("submit-lead.php", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
      })
      .then(res => res.json())
      .then(res => {
        console.log("Lead captured:", res);
        goThanks();
      })
      .catch(err => {
        console.error("Error capturing lead:", err);
        goThanks(); // Fallback redirect anyway so the customer isn't stuck!
      });
    },
  };

  return (
    <>
      <TopBar data={DATA} />
      <Header data={DATA} onCTA={scrollToForm} />
      <main>
        <Hero data={DATA} leadFormRef={leadFormRef} formProps={formProps} headline={copy.headline} />
        <Stats />
        <Why />
        {t.showFinishes && <Finishes />}
        <Products onQuote={scrollToForm} />
        {t.showGallery && <Gallery />}
        <Process />
        {t.showClients && <Clients />}
        {t.showReviews && <Reviews />}
        <FAQ />
        <FinalCTA data={DATA} onQuote={scrollToForm} />
        <Footer />
      </main>
      <FloatingCTA data={DATA} onQuote={scrollToForm} />

      <TweaksPanel title="Landing Page Tweaks">
        <TweakSection label="Brand colors">
          <TweakColor
            label="Primary (deep)"
            value={t.brandColor}
            options={["#0e4b8c","#0e2c4e","#103a6e","#0b3b2e","#1a1a1a"]}
            onChange={(v) => setTweak('brandColor', v)}
          />
          <TweakColor
            label="CTA accent"
            value={t.accentColor}
            options={["#e85a1a","#d62828","#f59e0b","#10b981","#2563eb"]}
            onChange={(v) => setTweak('accentColor', v)}
          />
        </TweakSection>

        <TweakSection label="Hero variant">
          <TweakRadio
            label="Angle"
            value={t.heroVariant}
            options={["Quote","Discount","Visit"]}
            onChange={(v) => setTweak('heroVariant', v)}
          />
          <TweakText
            label="Headline (Quote variant)"
            value={t.headline}
            onChange={(v) => setTweak('headline', v)}
          />
        </TweakSection>

        <TweakSection label="Lead form copy">
          <TweakText label="Form headline" value={t.formHeadline} onChange={(v) => setTweak('formHeadline', v)} />
          <TweakText label="Form sub" value={t.formSub} onChange={(v) => setTweak('formSub', v)} />
          <TweakText label="Offer ribbon" value={t.offerLine} onChange={(v) => setTweak('offerLine', v)} />
          <TweakText label="Submit button" value={t.ctaLabel} onChange={(v) => setTweak('ctaLabel', v)} />
        </TweakSection>

        <TweakSection label="Sections">
          <TweakToggle label="Show color finishes" value={t.showFinishes} onChange={(v) => setTweak('showFinishes', v)} />
          <TweakToggle label="Show installation gallery" value={t.showGallery} onChange={(v) => setTweak('showGallery', v)} />
          <TweakToggle label="Show esteemed clients" value={t.showClients} onChange={(v) => setTweak('showClients', v)} />
          <TweakToggle label="Show customer reviews" value={t.showReviews} onChange={(v) => setTweak('showReviews', v)} />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

/* ---------- helpers ---------- */
function hexToRgb(h) {
  const m = h.replace('#','').match(/^([0-9a-f]{6})$/i);
  if (!m) return { r: 0, g: 0, b: 0 };
  const n = parseInt(m[1], 16);
  return { r: (n>>16)&255, g: (n>>8)&255, b: n&255 };
}
function rgbToHex({ r, g, b }) {
  const c = (v) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2,'0');
  return `#${c(r)}${c(g)}${c(b)}`;
}
function shade(hex, amount) {
  const { r, g, b } = hexToRgb(hex);
  if (amount < 0) { const k = 1 + amount; return rgbToHex({ r: r*k, g: g*k, b: b*k }); }
  return rgbToHex({ r: r + (255-r)*amount, g: g + (255-g)*amount, b: b + (255-b)*amount });
}
function tint(hex, amount) {
  const { r, g, b } = hexToRgb(hex);
  return rgbToHex({ r: r + (255-r)*amount, g: g + (255-g)*amount, b: b + (255-b)*amount });
}

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