/** @jsxRuntime classic */
const { useEffect, useMemo, useState } = React;

const services = [
  {
    title: "Rooftop Solar",
    text: "Residential and commercial on-grid systems with net metering, subsidy guidance and 25-year output planning.",
    chips: ["Net Metering", "Subsidy Filing", "3-500 kW"],
  },
  {
    title: "Hybrid Solar",
    text: "Solar plus battery backup for homes, clinics, offices and factories that need power security.",
    chips: ["Battery Storage", "Grid-Tied", "Backup Ready"],
  },
  {
    title: "Community Solar",
    text: "Shared solar planning for societies, hospitals, institutions and commercial clusters.",
    chips: ["Group Metering", "Revenue Share", "50-500 kW"],
  },
  {
    title: "AMC & Maintenance",
    text: "Cleaning, inspection, generation review, safety checks and fault response for existing systems.",
    chips: ["Panel Cleaning", "Inverter Checks", "Performance Audit"],
  },
];

const cities = ["Delhi", "Gurugram", "Noida", "Faridabad", "Ghaziabad", "Manesar", "Bhiwadi"];
const indianStates = [
  "Andaman and Nicobar Islands",
  "Andhra Pradesh",
  "Arunachal Pradesh",
  "Assam",
  "Bihar",
  "Chandigarh",
  "Chhattisgarh",
  "Dadra and Nagar Haveli and Daman and Diu",
  "Delhi",
  "Goa",
  "Gujarat",
  "Haryana",
  "Himachal Pradesh",
  "Jammu and Kashmir",
  "Jharkhand",
  "Karnataka",
  "Kerala",
  "Ladakh",
  "Lakshadweep",
  "Madhya Pradesh",
  "Maharashtra",
  "Manipur",
  "Meghalaya",
  "Mizoram",
  "Nagaland",
  "Odisha",
  "Puducherry",
  "Punjab",
  "Rajasthan",
  "Sikkim",
  "Tamil Nadu",
  "Telangana",
  "Tripura",
  "Uttar Pradesh",
  "Uttarakhand",
  "West Bengal",
];
const solarTypes = ["On-grid rooftop", "Hybrid with battery", "Off-grid solar", "Commercial / Industrial"];
const industries = ["Homes", "Hospitals", "Schools", "Hotels", "Factories", "Warehouses", "Apartments"];
const faqs = [
  ["How much does rooftop solar cost?", "Cost depends on system size, roof structure, inverter type, subsidy eligibility and net-metering scope. Use the calculator to size the project first."],
  ["Do you handle subsidy and net metering?", "Yes. Preserve Green Power can guide documentation, inspection coordination and DISCOM milestones for eligible projects."],
  ["Can apartments or builder floors use solar?", "Yes. Rooftop, shared, balcony and hybrid options can be planned depending on ownership, roof rights and metering."],
  ["How fast is the payback?", "Many rooftop systems recover cost in 3-6 years depending on tariff, usage pattern, subsidy and financing."],
  ["Do you provide AMC after installation?", "Yes. AMC can include cleaning, inspection, generation tracking, inverter checks, earthing review and troubleshooting."],
];

const formatInr = (value) => new Intl.NumberFormat("en-IN", { maximumFractionDigits: 0 }).format(Math.round(value || 0));

function calculateSolar(input) {
  const monthlyUnits = input.calcMode === "units" ? input.monthlyUnits : input.monthlyBill / input.unitRate;
  const sizeByBill = input.calcMode === "roof" ? 500 : monthlyUnits / 120;
  const roofFactor = input.roofType === "Metal Sheet" ? 115 : input.roofType === "Mixed" ? 105 : 100;
  const sizeByRoof = input.roofArea / roofFactor;
  const systemSize = Math.max(1, Math.min(500, Math.round(Math.min(sizeByBill, sizeByRoof) * 10) / 10));
  const monthlyGeneration = Math.round(systemSize * 120);
  const monthlySavings = Math.round(input.calcMode === "roof"
    ? monthlyGeneration * input.unitRate
    : Math.min(input.monthlyBill * 0.92, monthlyGeneration * input.unitRate));
  const projectCost = Math.round(systemSize * (input.customerType === "Business" ? 52000 : 58000));
  const centralSubsidy = input.customerType === "Home" && input.solarType === "On-grid rooftop"
    ? systemSize < 2
      ? Math.round(Math.min(systemSize, 1) * 30000)
      : systemSize < 3
        ? Math.round(60000 + ((systemSize - 2) * 18000))
        : 78000
    : 0;
  const subsidyEstimate = Math.min(78000, centralSubsidy);
  const netCost = Math.max(projectCost - subsidyEstimate, 0);
  const paybackYears = Math.max(1.2, Math.round((netCost / Math.max(monthlySavings * 12, 1)) * 10) / 10);
  const co2Saved = Math.round(monthlyGeneration * 0.82 * 12);
  const moduleWatt = systemSize > 30 ? 580 : 550;
  const panelCount = Math.max(2, Math.ceil((systemSize * 1000) / moduleWatt));
  const inverterPhase = input.solarType === "Hybrid with battery" || input.batteryBackup
    ? systemSize >= 6 || input.customerType === "Business"
      ? "Three phase hybrid"
      : "Single phase hybrid"
    : input.solarType === "Off-grid solar"
    ? "Off-grid inverter"
    : systemSize >= 6 || input.customerType === "Business" || input.solarType === "Commercial / Industrial"
      ? "Three phase on-grid"
      : "Single phase on-grid";
  const areaFit = input.roofArea >= systemSize * roofFactor ? "Fits available roof" : "Needs roof check";
  const kitType = input.solarType === "Hybrid with battery" || input.batteryBackup
    ? "Hybrid solar kit"
    : input.solarType === "Off-grid solar"
      ? "Off-grid solar kit"
      : input.customerType === "Business" || input.solarType === "Commercial / Industrial"
        ? "Commercial on-grid kit"
        : "Residential on-grid kit";
  const subsidyStatus = subsidyEstimate > 0
    ? "Central subsidy estimate included"
    : input.customerType === "Home"
      ? "Subsidy depends on system type"
      : "Commercial subsidy not assumed";
  const stateBenefit = ["Uttar Pradesh", "Bihar", "Haryana", "Delhi", "Gujarat"].includes(input.state)
    ? "State/DISCOM benefit check recommended"
    : "Verify with state DISCOM";

  return { systemSize, monthlyGeneration, monthlySavings, projectCost, subsidyEstimate, netCost, paybackYears, co2Saved, moduleWatt, panelCount, inverterPhase, areaFit, kitType, subsidyStatus, stateBenefit };
}

function buildLeadMessage(lead) {
  return [
    `New solar enquiry from ${lead.name}`,
    `Phone: ${lead.phone}`,
    lead.email ? `Email: ${lead.email}` : "",
    `City: ${lead.city}`,
    `State: ${lead.state}`,
    lead.pincode ? `Pincode: ${lead.pincode}` : "",
    `Customer type: ${lead.customerType}`,
    `Solar type: ${lead.solarType}`,
    `Service: ${lead.service}`,
    `Monthly bill: Rs ${formatInr(lead.monthlyBill)}`,
    `Roof area: ${formatInr(lead.roofArea)} sq ft`,
    `Estimated system: ${lead.systemSize} kW`,
    `Estimated saving: Rs ${formatInr(lead.monthlySavings)}/month`,
    `Subsidy estimate: Rs ${formatInr(lead.subsidyEstimate)} (${lead.subsidyStatus})`,
    `Estimated payback: ${lead.paybackYears} years`,
    `Suggested kit: ${lead.kitType}`,
    `Panel count: ${lead.panelCount} panels of ${lead.moduleWatt}W`,
    `Inverter: ${lead.inverterPhase}`,
    lead.message ? `Message: ${lead.message}` : "",
  ].filter(Boolean).join("\n");
}

function App() {
  const [config] = useState({
    whatsappNumber: "919006616900",
    primaryPhone: "919006616900",
    secondaryPhone: "917070993139",
    landline: "01244044461",
    salesEmail: "info@preservegreenindia.com",
    gurgaonAddress: "Unit No: 812, 8th Floor, ILD Trade Centre, Sector-47, Sohna Road, Gurgaon-122018, Haryana",
    patnaAddress: "103, Korada Enclave, Rukunpura, Bailey Road, Patna -800014",
    facebookUrl: "#",
    instagramUrl: "#",
    linkedinUrl: "#",
    youtubeUrl: "#",
  });
  const [quoteOpen, setQuoteOpen] = useState(false);
  const [activeService, setActiveService] = useState("Rooftop Solar");
  const [activeHeroSlide, setActiveHeroSlide] = useState(0);
  const [cookiesAccepted, setCookiesAccepted] = useState(false);
  const [saving, setSaving] = useState(false);
  const [toast, setToast] = useState("");
  const [calc, setCalc] = useState({
    calcMode: "bill",
    customerType: "Home",
    state: "Haryana",
    city: "Gurgaon",
    monthlyBill: 5000,
    monthlyUnits: 625,
    unitRate: 8,
    roofArea: 500,
    roofType: "RCC Slab",
    solarType: "On-grid rooftop",
    batteryBackup: false,
  });
  const [lead, setLead] = useState({
    name: "",
    phone: "",
    email: "",
    city: "Delhi",
    pincode: "",
    service: "Rooftop Solar",
    message: "",
  });

  const result = useMemo(() => calculateSolar(calc), [calc]);

  const heroSlides = [
    {
      title: "Residential rooftop solar",
      note: "High-efficiency rooftop systems for homes, apartments and builder floors.",
      image: "assets/banner-residential-rooftop.png",
    },
    {
      title: "Commercial and industrial solar",
      note: "Engineered rooftop solar for offices, warehouses, factories and institutions.",
      image: "assets/banner-commercial-industrial.png",
    },
    {
      title: "Subsidy and net-metering support",
      note: "Guidance for residential subsidy, DISCOM process and net-metering documentation.",
      image: "assets/banner-subsidy-consultation.png",
    },
  ];

  useEffect(() => {
    const timer = window.setInterval(() => {
      setActiveHeroSlide((current) => (current + 1) % heroSlides.length);
    }, 4500);

    return () => window.clearInterval(timer);
  }, []);

  useEffect(() => {
    setCookiesAccepted(localStorage.getItem("preserve-cookie-consent") === "accepted");
  }, []);

  const updateCalc = (field, value) => setCalc((current) => ({ ...current, [field]: value }));
  const updateLead = (field, value) => setLead((current) => ({ ...current, [field]: value }));

  const whatsappText = encodeURIComponent(
    `Hi Preserve Green Power India, I need a solar quote.\nState: ${calc.state}\nCity: ${calc.city}\nSolar type: ${calc.solarType}\nBill: Rs ${formatInr(calc.monthlyBill)}/month\nEstimated system: ${result.systemSize} kW\nSuggested kit: ${result.kitType}\nSubsidy estimate: Rs ${formatInr(result.subsidyEstimate)}\nService: ${lead.service}`
  );
  const whatsappUrl = `https://wa.me/${config.whatsappNumber}?text=${whatsappText}`;

  const submitLead = async (event) => {
    event.preventDefault();
    setSaving(true);
    setToast("");

    const payload = {
      ...lead,
      ...calc,
      ...result,
      customerType: calc.customerType,
      monthlyBill: Number(calc.monthlyBill),
      roofArea: Number(calc.roofArea),
      source: "website-react",
    };

    const localLeads = JSON.parse(localStorage.getItem("preserve-green-power-leads") || "[]");
    localLeads.unshift({ ...payload, createdAt: new Date().toISOString() });
    localStorage.setItem("preserve-green-power-leads", JSON.stringify(localLeads));

    const mailSubject = encodeURIComponent("New solar enquiry");
    const mailBody = encodeURIComponent(buildLeadMessage(payload));
    window.open(`mailto:${config.salesEmail}?subject=${mailSubject}&body=${mailBody}`, "_self");

    setToast("Enquiry prepared for email and saved in this browser.");
    setLead({ name: "", phone: "", email: "", city: calc.city, pincode: "", service: lead.service, message: "" });
    setSaving(false);
  };

  return (
    <>
      <TopBar config={config} whatsappUrl={whatsappUrl} />
      <Header openQuote={() => setQuoteOpen(true)} />
      <main>
        <Hero
          openQuote={() => setQuoteOpen(true)}
          result={result}
          slides={heroSlides}
          activeSlide={activeHeroSlide}
          setActiveSlide={setActiveHeroSlide}
        />
        <Calculator calc={calc} result={result} updateCalc={updateCalc} openQuote={() => setQuoteOpen(true)} />
        <SubsidyGuide openQuote={() => setQuoteOpen(true)} />
        <AboutSection />
        <ServiceShowcase activeService={activeService} setActiveService={setActiveService} openQuote={() => setQuoteOpen(true)} />
        <WhySection />
        <InstallationVideoSection openQuote={() => setQuoteOpen(true)} />
        <CaseStudy />
        <IndustryCitySection />
        <Reviews />
        <FAQ />
      </main>
      <Footer config={config} whatsappUrl={whatsappUrl} />
      <StickySurveyBar openQuote={() => setQuoteOpen(true)} />
      <FloatingSocialIcons config={config} whatsappUrl={whatsappUrl} />
      <BackToTop />
      <CookieNotice accepted={cookiesAccepted} onAccept={() => {
        localStorage.setItem("preserve-cookie-consent", "accepted");
        setCookiesAccepted(true);
      }} />
      <QuoteModal
        open={quoteOpen}
        close={() => setQuoteOpen(false)}
        lead={lead}
        updateLead={updateLead}
        calc={calc}
        updateCalc={updateCalc}
        result={result}
        submitLead={submitLead}
        saving={saving}
        toast={toast}
        whatsappUrl={whatsappUrl}
        config={config}
      />
    </>
  );
}

function AboutSection() {
  return (
    <section className="about-section" id="about">
      <div>
        <span className="pill">About Preserve Green Power India</span>
        <h2>Innovative, reliable and sustainable solar power solutions.</h2>
      </div>
      <p>
        Preserve Green Power India Private Limited is a forward-thinking solar energy company committed to delivering innovative, reliable, and sustainable power solutions for both domestic and commercial clients. With a strong focus on the latest advancements in solar technology, we specialize in the design, installation, and maintenance of high-efficiency solar panel systems tailored to meet diverse energy needs.
      </p>
    </section>
  );
}

function TopBar({ config, whatsappUrl }) {
  return (
    <div className="topbar">
      <span>24x7 customer support</span>
      <div>
        <a href={`tel:+${config.primaryPhone}`}>+91 9006616900</a>
        <a href={`tel:+${config.secondaryPhone}`}>+91 7070993139</a>
      </div>
    </div>
  );
}

function Header({ openQuote }) {
  return (
    <header className="header">
      <a className="brand" href="#home">
        <img src="assets/Preserve_Green_Logo1.jpg" alt="Preserve Green Power India logo" />
      </a>
      <nav>
        <a href="#calculator">Calculator</a>
        <a href="#services">Services</a>
        <a href="#commercial">Commercial</a>
        <a href="#reviews">Reviews</a>
        <a href="#faq">FAQ</a>
      </nav>
      <button className="icon-button" type="button" onClick={() => document.querySelector("#calculator").scrollIntoView({ behavior: "smooth" })}>Calc</button>
      <button className="quote-button" type="button" onClick={openQuote}>Get Free Quote</button>
    </header>
  );
}

function Hero({ openQuote, result, slides, activeSlide, setActiveSlide }) {
  const active = slides[activeSlide];

  return (
    <section className="hero" id="home">
      <div className={`hero-banner banner-${activeSlide + 1}`} style={{ backgroundImage: `linear-gradient(90deg, rgba(8, 32, 24, 0.88) 0%, rgba(8, 32, 24, 0.62) 42%, rgba(8, 32, 24, 0.12) 100%), url(${active.image})` }}>
        <div>
          <span className="pill">Preserve solar journey</span>
          <h2>{active.title}</h2>
          <p>{active.note}</p>
        </div>
        <div className="banner-metrics">
          <span><b>{result.systemSize} kW</b> recommended system</span>
          <span><b>Rs {formatInr(result.monthlySavings)}</b> monthly saving estimate</span>
          <span><b>{result.panelCount}</b> panel layout estimate</span>
        </div>
        <div className="hero-dots" aria-label="Hero banner selector">
          {slides.map((slide, index) => (
            <button
              className={index === activeSlide ? "active" : ""}
              type="button"
              aria-label={`Show ${slide.title}`}
              onClick={() => setActiveSlide(index)}
              key={slide.title}
            ></button>
          ))}
        </div>
      </div>
      <div className="hero-copy">
        <span className="pill">Solar engineered for measurable savings</span>
        <h1>Clean energy systems designed around your roof, bill and future load.</h1>
        <p>From Gurgaon offices to Patna homes and commercial sites across India, we plan high-efficiency solar systems with practical engineering, transparent estimates and dependable service.</p>
        <div className="hero-actions">
          <button className="primary-cta" type="button" onClick={openQuote}>Get Free Quote</button>
          <a className="soft-cta" href="#calculator">Calculate Your Savings</a>
        </div>
        <div className="trust-row">
          <a href="#reviews"><strong>4.8 rated service</strong></a>
          <a href="#subsidy"><span>Net metering</span></a>
          <a href="#subsidy"><span>Subsidy guidance</span></a>
          <a href="#services"><span>AMC support</span></a>
        </div>
      </div>
      <div className="hero-showcase">
        <SolarIllustration result={result} activeSlide={activeSlide} />
      </div>
    </section>
  );
}

function SolarIllustration({ result, activeSlide }) {
  return (
    <div className={`solar-scene scene-${activeSlide + 1}`} aria-label="Rooftop solar installation scenes">
      {[0, 1, 2].map((item) => (
        <div className={`building b${item + 1}`} key={item}>
          <div className="roof"><span></span><span></span><span></span></div>
          <div className="windows">{Array.from({ length: 8 }).map((_, i) => <i key={i}></i>)}</div>
        </div>
      ))}
      <div className="saving-card one"><small>{result.systemSize} kW system</small><b>Rs {formatInr(result.monthlySavings)}</b><span>/month</span></div>
      <div className="saving-card two"><small>Payback</small><b>{result.paybackYears} yrs</b><span>estimated</span></div>
    </div>
  );
}

function Calculator({ calc, result, updateCalc, openQuote }) {
  return (
    <section className="calculator-section" id="calculator">
      <div className="section-title">
        <span className="pill">Solar kit calculator</span>
        <h2>Estimate savings and see the system kit your roof may need.</h2>
      </div>
      <div className="calculator-grid">
        <div className="calc-controls">
          <ModeCards value={calc.calcMode} onChange={(value) => updateCalc("calcMode", value)} />
          <div className="calculator-step">
            <b>Step two</b>
            <h3>Your location and customer type</h3>
          </div>
          <SelectField label="State / UT" value={calc.state} options={indianStates} onChange={(value) => updateCalc("state", value)} />
          <TextField label="City / District" value={calc.city} onChange={(value) => updateCalc("city", value)} placeholder="e.g. Gurgaon, Patna, Ranchi" />
          <Toggle label="I am a" value={calc.customerType} options={["Home", "Business"]} onChange={(value) => updateCalc("customerType", value)} />
          <SelectField label="Type of solar" value={calc.solarType} options={solarTypes} onChange={(value) => {
            updateCalc("solarType", value);
            updateCalc("batteryBackup", value === "Hybrid with battery");
            if (value === "Commercial / Industrial") updateCalc("customerType", "Business");
            if (value !== "Commercial / Industrial") updateCalc("customerType", "Home");
          }} />
          <div className="calculator-step">
            <b>Step three</b>
            <h3>{calc.calcMode === "bill" ? "Enter monthly electricity bill" : calc.calcMode === "units" ? "Enter monthly electricity units" : "Enter available roof area"}</h3>
          </div>
          {calc.calcMode === "bill" && (
            <Range label="Monthly bill" prefix="Rs" min={1000} max={300000} step={500} value={calc.monthlyBill} onChange={(value) => {
              updateCalc("monthlyBill", value);
              updateCalc("monthlyUnits", Math.round(value / calc.unitRate));
            }} />
          )}
          {calc.calcMode === "units" && (
            <Range label="Monthly units" suffix="units" min={100} max={20000} step={25} value={calc.monthlyUnits} onChange={(value) => {
              updateCalc("monthlyUnits", value);
              updateCalc("monthlyBill", Math.round(value * calc.unitRate));
            }} />
          )}
          <Range label="Roof area" suffix="sq ft" min={100} max={20000} step={50} value={calc.roofArea} onChange={(value) => updateCalc("roofArea", value)} />
          <Toggle label="Roof type" value={calc.roofType} options={["RCC Slab", "Metal Sheet", "Mixed"]} onChange={(value) => updateCalc("roofType", value)} />
          <label className="check-row">
            <input type="checkbox" checked={calc.batteryBackup} onChange={(event) => updateCalc("batteryBackup", event.target.checked)} />
            Add battery backup requirement
          </label>
        </div>
        <div className="calc-results">
          <span className="pill">Live result</span>
          <strong>{result.systemSize} kW</strong>
          <p>
            {calc.calcMode === "bill" && `Recommended solar system for a Rs ${formatInr(calc.monthlyBill)} monthly bill in ${calc.city}.`}
            {calc.calcMode === "units" && `Recommended solar system for ${formatInr(calc.monthlyUnits)} monthly units in ${calc.city}.`}
            {calc.calcMode === "roof" && `Estimated solar potential for ${formatInr(calc.roofArea)} sq ft of shadow-free roof area in ${calc.city}.`}
          </p>
          <div className="kit-strip">
            <div>
              <span>Suggested kit</span>
              <b>{result.kitType}</b>
            </div>
            <div>
              <span>Panel layout</span>
              <b>{result.panelCount} x {result.moduleWatt}W</b>
            </div>
            <div>
              <span>Inverter</span>
              <b>{result.inverterPhase}</b>
            </div>
          </div>
          <div className="result-cards">
            <Metric label="Monthly savings" value={`Rs ${formatInr(result.monthlySavings)}`} />
            <Metric label="Monthly generation" value={`${formatInr(result.monthlyGeneration)} units`} />
            <Metric label="Project cost" value={`Rs ${formatInr(result.projectCost)}`} />
            <Metric label="Central subsidy" value={`Rs ${formatInr(result.subsidyEstimate)}`} />
            <Metric label="Payback" value={`${result.paybackYears} years`} />
            <Metric label="Roof fit" value={result.areaFit} />
          </div>
          <div className="subsidy-note">
            <b>{result.subsidyStatus}</b>
            <span>{result.stateBenefit}. Final subsidy depends on residential eligibility, DISCOM approval, net-metering and current government portal rules.</span>
          </div>
          <div className="quote-checklist">
            <span>Quote report includes</span>
            <ul>
              <li>Panel and inverter sizing</li>
              <li>Roof area and shadow check</li>
              <li>Subsidy/net-metering guidance</li>
              <li>25-year performance planning</li>
            </ul>
          </div>
          <button className="primary-cta wide" type="button" onClick={openQuote}>Get My Full Report</button>
        </div>
      </div>
    </section>
  );
}

function SubsidyGuide({ openQuote }) {
  const subsidyRows = [
    ["1 kW", "Rs 60,000 - Rs 70,000", "Rs 30,000", "Rs 30,000 - Rs 40,000"],
    ["2 kW", "Rs 1,20,000 - Rs 1,40,000", "Rs 60,000", "Rs 60,000 - Rs 80,000"],
    ["3 kW", "Rs 1,80,000 - Rs 2,00,000", "Rs 78,000", "Rs 1,00,000 - Rs 1,20,000"],
    ["4 kW+", "Varies by site", "Up to Rs 78,000", "Depends on final system cost"],
  ];
  const documents = ["Aadhaar card", "Latest electricity bill", "Bank details", "Address proof", "Mobile number", "Rooftop ownership proof"];
  const steps = [
    "Register on the national solar portal",
    "Submit consumer and DISCOM details",
    "Select approved vendor and system size",
    "Install rooftop solar with certified equipment",
    "Complete DISCOM inspection and net meter",
    "Submit commissioning details for subsidy credit",
  ];
  const reminders = [
    "Subsidy is generally for residential rooftop solar, not commercial or industrial projects.",
    "Use the same name and consumer details as your electricity connection where required.",
    "Keep bank details ready because subsidy is credited directly to the beneficiary account.",
    "Do not finalize capacity only from subsidy. Match it to your load, roof area and future usage.",
  ];

  return (
    <section className="subsidy-section" id="subsidy">
      <div className="section-title">
        <span className="pill">PM Surya Ghar subsidy guide</span>
        <h2>Help your family understand subsidy before they install solar.</h2>
      </div>
      <div className="subsidy-layout">
        <div className="subsidy-intro">
          <h3>Who can apply?</h3>
          <p>The central subsidy is mainly for eligible residential households with a grid-connected electricity connection and usable rooftop space. Commercial and industrial projects are normally estimated without this residential subsidy.</p>
          <div className="eligibility-list">
            <span>Residential household</span>
            <span>Own rooftop or valid roof rights</span>
            <span>Registered DISCOM consumer</span>
            <span>Net-metering eligible connection</span>
          </div>
          <button className="primary-cta" type="button" onClick={openQuote}>Check My Eligibility</button>
        </div>
        <div className="subsidy-table-wrap">
          <table className="subsidy-table">
            <thead>
              <tr>
                <th>System</th>
                <th>Typical cost</th>
                <th>Central subsidy</th>
                <th>After subsidy</th>
              </tr>
            </thead>
            <tbody>
              {subsidyRows.map((row) => (
                <tr key={row[0]}>
                  {row.map((cell) => <td key={cell}>{cell}</td>)}
                </tr>
              ))}
            </tbody>
          </table>
          <p className="table-note">Final subsidy depends on current government rules, application approval, DISCOM process and residential eligibility.</p>
        </div>
      </div>
      <div className="subsidy-cards">
        <article>
          <h3>Documents needed</h3>
          <ul>{documents.map((item) => <li key={item}>{item}</li>)}</ul>
        </article>
        <article>
          <h3>Application path</h3>
          <ol>{steps.map((item) => <li key={item}>{item}</li>)}</ol>
        </article>
        <article>
          <h3>Roof planning shortcut</h3>
          <p>As a quick thumb rule, plan around 100 sq ft of shadow-free space per 1 kW. A 3 kW system generally needs around 300 sq ft, while a 5 kW system needs around 500 sq ft.</p>
          <p>Net metering adjusts exported daytime solar generation against grid use, helping reduce monthly bills.</p>
        </article>
        <article>
          <h3>Before applying</h3>
          <ul>{reminders.map((item) => <li key={item}>{item}</li>)}</ul>
        </article>
      </div>
    </section>
  );
}

function ModeCards({ value, onChange }) {
  const modes = [
    { id: "bill", title: "Monthly Bill", text: "Use your electricity bill amount", icon: "Rs" },
    { id: "units", title: "Monthly Units", text: "Use kWh units from your bill", icon: "kWh" },
    { id: "roof", title: "Roof Area", text: "Use available shadow-free area", icon: "sq ft" },
  ];

  return (
    <div className="mode-section">
      <div className="calculator-step">
        <b>Step one</b>
        <h3>How would you like to calculate?</h3>
      </div>
      <div className="mode-cards">
        {modes.map((mode) => (
          <button className={value === mode.id ? "active" : ""} type="button" onClick={() => onChange(mode.id)} key={mode.id}>
            <strong>{mode.icon}</strong>
            <span>{mode.title}</span>
            <small>{mode.text}</small>
          </button>
        ))}
      </div>
    </div>
  );
}

function SelectField({ label, value, options, onChange }) {
  return (
    <label className="select-field">
      <span>{label}</span>
      <select value={value} onChange={(event) => onChange(event.target.value)}>
        {options.map((option) => <option value={option} key={option}>{option}</option>)}
      </select>
    </label>
  );
}

function TextField({ label, value, onChange, placeholder }) {
  return (
    <label className="text-field">
      <span>{label}</span>
      <input value={value} onChange={(event) => onChange(event.target.value)} placeholder={placeholder} />
    </label>
  );
}

function Toggle({ label, value, options, onChange }) {
  return (
    <div className="toggle-group">
      <span>{label}</span>
      <div>{options.map((option) => <button className={option === value ? "active" : ""} type="button" onClick={() => onChange(option)} key={option}>{option}</button>)}</div>
    </div>
  );
}

function Range({ label, prefix = "", suffix = "", min, max, step, value, onChange }) {
  return (
    <label className="range-row">
      <span>{label}</span>
      <div className="range-heading">
        <b>{prefix} {formatInr(value)} {suffix}</b>
        <input
          className="range-number"
          type="number"
          min={min}
          max={max}
          step={step}
          value={value}
          onChange={(event) => onChange(Number(event.target.value))}
        />
      </div>
      <input type="range" min={min} max={max} step={step} value={value} onChange={(event) => onChange(Number(event.target.value))} />
    </label>
  );
}

function Metric({ label, value }) {
  return <div className="metric"><span>{label}</span><b>{value}</b></div>;
}

function ServiceShowcase({ activeService, setActiveService, openQuote }) {
  const selected = services.find((service) => service.title === activeService) || services[0];
  return (
    <section className="services-section" id="services">
      <div className="section-title">
        <span className="pill">Built for every rooftop</span>
        <h2>One solar partner for design, installation, upgrades and long-term care.</h2>
      </div>
      <div className="service-grid">
        {services.map((service) => (
          <button className={`service-card ${activeService === service.title ? "active" : ""}`} type="button" onClick={() => setActiveService(service.title)} key={service.title}>
            <h3>{service.title}</h3>
            <p>{service.text}</p>
            <div>{service.chips.map((chip) => <span key={chip}>{chip}</span>)}</div>
          </button>
        ))}
      </div>
      <div className="service-detail">
        <div>
          <span className="pill">{selected.title}</span>
          <h3>{selected.text}</h3>
          <p>Preserve Green Power India can package survey, engineering, equipment, permissions, installation, monitoring and AMC into one clear project plan.</p>
        </div>
        <button className="primary-cta" type="button" onClick={openQuote}>Get Quote for {selected.title}</button>
      </div>
    </section>
  );
}

function WhySection() {
  return (
    <section className="why-section">
      <div className="section-title">
        <span className="pill">Preserve Solar Audit</span>
        <h2>We do not guess your solar capacity. We map the project before quoting.</h2>
      </div>
      <div className="audit-panel">
        <div>
          <strong>01</strong>
          <span>Bill Pattern</span>
          <p>We review monthly consumption, tariff, sanctioned load and daytime usage before sizing the plant.</p>
        </div>
        <div>
          <strong>02</strong>
          <span>Roof Readiness</span>
          <p>We check shadow-free area, access, structure, panel orientation, wiring route and inverter placement.</p>
        </div>
        <div>
          <strong>03</strong>
          <span>Approval Path</span>
          <p>We identify net-metering, subsidy, DISCOM documentation and site-specific approval requirements.</p>
        </div>
        <div>
          <strong>04</strong>
          <span>Lifetime Care</span>
          <p>We plan cleaning, safety checks, monitoring, AMC and generation review so output stays dependable.</p>
        </div>
      </div>
      <div className="steps compact-steps">
        {["Survey", "Design", "Install", "Maintain"].map((step, index) => (
          <article key={step}>
            <b>{String(index + 1).padStart(2, "0")}</b>
            <h3>{step}</h3>
            <p>{["On-site roof, load and billing assessment.", "Panel layout, inverter sizing and savings model.", "Safe structure, cabling, earthing and commissioning.", "Cleaning, performance checks and service support."][index]}</p>
          </article>
        ))}
      </div>
    </section>
  );
}

function InstallationVideoSection({ openQuote }) {
  const stages = [
    "Roof survey and marking",
    "Mounting structure fixing",
    "Panel placement and wiring",
    "Inverter, earthing and protection",
    "Testing and commissioning",
  ];

  return (
    <section className="install-video-section" id="installation">
      <div className="video-copy">
        <span className="pill">Installation walkthrough</span>
        <h2>Show customers exactly how a solar project comes together.</h2>
        <p>Add your real project video here so customers can see the survey, structure work, panel installation, inverter setup, safety checks and final commissioning.</p>
        <button className="primary-cta" type="button" onClick={openQuote}>Book a Site Survey</button>
      </div>
      <div className="video-panel">
        <div className="video-frame">
          <div className="play-button">Play</div>
          <span>Project installation video</span>
        </div>
        <ol>
          {stages.map((stage) => <li key={stage}>{stage}</li>)}
        </ol>
      </div>
    </section>
  );
}

function BackToTop() {
  return (
    <button
      className="back-to-top"
      type="button"
      aria-label="Back to top"
      onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}
    >
      ↑
    </button>
  );
}

function CookieNotice({ accepted, onAccept }) {
  if (accepted) return null;

  return (
    <div className="cookie-notice">
      <p>
        This website uses cookies or similar technologies to enhance your browsing experience.
        <br />
        By continuing to use our website, you agree to our privacy policy.
      </p>
      <button type="button" onClick={onAccept}>I Agree</button>
    </div>
  );
}

function CaseStudy() {
  return (
    <section className="case-section">
      <div className="case-visual">
        <div className="video-play">Play</div>
      </div>
      <div>
        <span className="pill">Real installation style</span>
        <h2>Show customers what happens after they enquire.</h2>
        <p>Use this section for your own case-study video or photos: site survey, structure, panel placement, inverter work, net-metering and final generation report.</p>
        <div className="case-stats">
          <Metric label="Sample system" value="5 kW" />
          <Metric label="Estimated saving" value="Rs 6,500/mo" />
          <Metric label="Install time" value="3-5 days" />
        </div>
      </div>
    </section>
  );
}

function IndustryCitySection() {
  return (
    <section className="commercial-section" id="commercial">
      <div>
        <span className="pill">Commercial + city pages</span>
        <h2>Capture high-intent searches for every customer type.</h2>
        <p>Dedicated content blocks help customers see themselves in the site, from hospitals and schools to factories and apartments.</p>
      </div>
      <div className="tag-cloud">
        {industries.map((item) => <span key={item}>Solar for {item}</span>)}
        {cities.map((city) => <span key={city}>Solar in {city}</span>)}
      </div>
    </section>
  );
}

function Reviews() {
  return (
    <section className="reviews-section" id="reviews">
      <div className="section-title">
        <span className="pill">Trust signals</span>
        <h2>Make every enquiry feel lower-risk.</h2>
      </div>
      <div className="review-grid">
        {["Clear explanation, fast survey and neat installation.", "The savings estimate helped us understand payback before committing.", "AMC team identified generation drop and fixed the issue quickly."].map((text, index) => (
          <article key={text}>
            <b>4.{8 - index} stars</b>
            <p>{text}</p>
            <span>{["Homeowner, Delhi", "Factory owner, Noida", "School admin, Gurugram"][index]}</span>
          </article>
        ))}
      </div>
    </section>
  );
}

function FAQ() {
  return (
    <section className="faq-section" id="faq">
      <div className="section-title">
        <span className="pill">Questions</span>
        <h2>Got questions? We have clear answers.</h2>
      </div>
      <div className="faq-list">
        {faqs.map(([question, answer], index) => <details open={index === 0} key={question}><summary>{question}</summary><p>{answer}</p></details>)}
      </div>
    </section>
  );
}

function QuoteModal({ open, close, lead, updateLead, calc, updateCalc, result, submitLead, saving, toast, whatsappUrl, config }) {
  if (!open) return null;

  return (
    <div className="modal-backdrop" role="dialog" aria-modal="true">
      <form className="quote-modal" onSubmit={submitLead}>
        <button className="close-button" type="button" onClick={close}>×</button>
        <span className="pill">Free quote in 60 seconds</span>
        <h2>Tell us where to send your solar report.</h2>
        <div className="modal-grid">
          <label>Name<input required value={lead.name} onChange={(e) => updateLead("name", e.target.value)} placeholder="Your full name" /></label>
          <label>Phone / WhatsApp<input required value={lead.phone} onChange={(e) => updateLead("phone", e.target.value)} placeholder="+91 98765 43210" /></label>
          <label>Email<input value={lead.email} onChange={(e) => updateLead("email", e.target.value)} placeholder="you@email.com" /></label>
          <label>State<select value={calc.state} onChange={(e) => updateCalc("state", e.target.value)}>{indianStates.map((state) => <option key={state}>{state}</option>)}</select></label>
          <label>City<input required value={lead.city} onChange={(e) => { updateLead("city", e.target.value); updateCalc("city", e.target.value || calc.city); }} placeholder="Delhi, Gurugram" /></label>
          <label>Pincode<input value={lead.pincode} onChange={(e) => updateLead("pincode", e.target.value)} placeholder="6-digit pincode" /></label>
          <label>Service<select value={lead.service} onChange={(e) => updateLead("service", e.target.value)}>{services.map((service) => <option key={service.title}>{service.title}</option>)}</select></label>
          <label>Type of Solar<select value={calc.solarType} onChange={(e) => updateCalc("solarType", e.target.value)}>{solarTypes.map((type) => <option key={type}>{type}</option>)}</select></label>
          <label>Monthly Bill<input type="number" value={calc.monthlyBill} onChange={(e) => updateCalc("monthlyBill", Number(e.target.value))} /></label>
          <label>Roof Area<input type="number" value={calc.roofArea} onChange={(e) => updateCalc("roofArea", Number(e.target.value))} /></label>
          <label className="full">Message<textarea value={lead.message} onChange={(e) => updateLead("message", e.target.value)} placeholder="Roof rights, connection type, society approval, or site notes"></textarea></label>
        </div>
        <div className="quote-summary">
          <Metric label="Estimated system" value={`${result.systemSize} kW`} />
          <Metric label="Monthly savings" value={`Rs ${formatInr(result.monthlySavings)}`} />
          <Metric label="Payback" value={`${result.paybackYears} yrs`} />
        </div>
        <div className="modal-actions">
          <button className="primary-cta" disabled={saving} type="submit">{saving ? "Saving..." : "Save Lead & Request Quote"}</button>
          <a className="soft-cta dark" href={whatsappUrl} target="_blank" rel="noreferrer">Continue on WhatsApp</a>
          <a className="soft-cta dark" href={`mailto:${config.salesEmail}`}>Email Sales</a>
        </div>
        {toast && <p className="toast">{toast}</p>}
      </form>
    </div>
  );
}

function IconMark({ type }) {
  if (type === "whatsapp") {
    return (
      <svg viewBox="0 0 32 32" aria-hidden="true">
        <path d="M16 4.5A10.8 10.8 0 0 0 6.7 20.8L5 27l6.4-1.6A10.8 10.8 0 1 0 16 4.5Zm0 2.2a8.6 8.6 0 0 1 7.3 13.2 8.5 8.5 0 0 1-10.9 3.2l-.5-.2-3.6.9 1-3.5-.3-.6A8.6 8.6 0 0 1 16 6.7Zm-3.6 4.5c-.2 0-.5.1-.7.3-.2.2-.8.8-.8 1.9s.8 2.2.9 2.3c.1.2 1.6 2.6 4 3.6 2 .9 2.4.7 2.8.7.4-.1 1.4-.6 1.6-1.1.2-.5.2-1 .1-1.1-.1-.1-.3-.2-.7-.4l-1-.5c-.3-.1-.6-.2-.8.2l-.6.8c-.2.2-.4.2-.7.1-.4-.2-1.4-.5-2.6-1.6-1-.9-1.6-2-1.8-2.3-.2-.3 0-.5.1-.7l.5-.6c.2-.2.2-.4.3-.6.1-.2 0-.4 0-.6l-.5-1.2c-.2-.5-.4-.5-.7-.5h-.4Z" />
      </svg>
    );
  }

  if (type === "call") {
    return (
      <svg viewBox="0 0 24 24" aria-hidden="true">
        <path d="M6.6 10.8c1.4 2.8 3.7 5.1 6.6 6.6l2.2-2.2c.3-.3.8-.4 1.2-.3 1.3.4 2.6.6 4 .6.7 0 1.2.5 1.2 1.2v3.5c0 .7-.5 1.2-1.2 1.2C10.4 21.9 2.1 13.6 2.1 3.4c0-.7.5-1.2 1.2-1.2h3.5c.7 0 1.2.5 1.2 1.2 0 1.4.2 2.8.6 4 .1.4 0 .9-.3 1.2l-1.7 2.2Z" />
      </svg>
    );
  }

  if (type === "mail") {
    return (
      <svg viewBox="0 0 24 24" aria-hidden="true">
        <path d="M3 5h18c.6 0 1 .4 1 1v12c0 .6-.4 1-1 1H3c-.6 0-1-.4-1-1V6c0-.6.4-1 1-1Zm9 8.1L4.8 7H4v.7l8 6.8 8-6.8V7h-.8L12 13.1Z" />
      </svg>
    );
  }

  return <span>{type}</span>;
}

function StickySurveyBar({ openQuote }) {
  return (
    <div className="sticky-survey-bar">
      <span>Talk to a solar engineer, not a salesperson - Free Site Survey</span>
      <button type="button" onClick={openQuote}>Get Free Quote</button>
      <a href="#calculator">Calculate Savings</a>
    </div>
  );
}

function FloatingSocialIcons({ config, whatsappUrl }) {
  const socials = [
    { label: "WhatsApp", href: whatsappUrl, icon: "whatsapp", external: true, primary: true },
    { label: "Call", href: `tel:+${config.primaryPhone}`, icon: "call" },
    { label: "Email", href: `mailto:${config.salesEmail}`, icon: "mail" },
    { label: "Facebook", href: config.facebookUrl, icon: "f", external: true },
    { label: "Instagram", href: config.instagramUrl, icon: "IG", external: true },
    { label: "LinkedIn", href: config.linkedinUrl, icon: "in", external: true },
    { label: "YouTube", href: config.youtubeUrl, icon: "YT", external: true },
  ];

  return (
    <div className="floating-socials" aria-label="Quick contact and social links">
      {socials.map((item) => (
        <a
          className={item.primary ? "primary-social" : ""}
          href={item.href}
          aria-label={item.label}
          title={item.label}
          target={item.external ? "_blank" : undefined}
          rel={item.external ? "noreferrer" : undefined}
          key={item.label}
        >
          <IconMark type={item.icon} />
        </a>
      ))}
    </div>
  );
}

function Footer({ config, whatsappUrl }) {
  return (
    <footer className="footer">
      <div>
        <img src="assets/Preserve_Green_Logo1.jpg" alt="" />
        <h2>Preserve Green Power India</h2>
        <p>Rooftop solar, hybrid solar, community solar, AMC and clean-energy advisory for Indian homes and businesses.</p>
      </div>
      <div>
        <h3>Services</h3>
        {services.map((service) => <a href="#services" key={service.title}>{service.title}</a>)}
        <a href="#installation">Installation Walkthrough</a>
      </div>
      <div>
        <h3>Tools</h3>
        <a href="#calculator">Solar Calculator</a>
        <a href="#subsidy">PM Surya Ghar Subsidy Guide</a>
        <a href="#commercial">Solar for MSME</a>
        <a href="#about">About Preserve</a>
        <a href="#reviews">Customer Reviews</a>
        <a href="#faq">FAQ</a>
      </div>
      <div>
        <h3>Contact</h3>
        <a href={`tel:+${config.primaryPhone}`}>+91 9006616900</a>
        <a href={`tel:+${config.secondaryPhone}`}>+91 7070993139</a>
        <a href={`tel:${config.landline}`}>Gurgaon: (0124) 4044461</a>
        <a href={`mailto:${config.salesEmail}`}>{config.salesEmail}</a>
      </div>
      <div className="footer-addresses">
        <h3>Offices</h3>
        <strong>Gurgaon Address</strong>
        <p>{config.gurgaonAddress}</p>
        <strong>Patna Address</strong>
        <p>{config.patnaAddress}</p>
      </div>
    </footer>
  );
}

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