/* CX-Feedback — homepage. Spec: website-specification.md section 6. */

function HomeHero() {
  return (
    <section
      id="top"
      className="relative flex-1 flex items-center pt-24 lg:pt-28 pb-10 lg:pb-14 bg-white overflow-hidden"
    >
      <div
        className="absolute inset-0 bg-cover bg-no-repeat bg-[position:left_center]"
        style={{ backgroundImage: "url('assets/child_bg4.png')" }}
        aria-hidden="true"
      />
      <div
        className="absolute inset-0 bg-gradient-to-r from-white/85 via-white/70 lg:via-white/60 to-white"
        aria-hidden="true"
      />
      <div className="relative max-w-container mx-auto px-5 sm:px-8 w-full">
        <div className="grid lg:grid-cols-12 gap-10 lg:gap-14 items-center">
          <div className="lg:col-span-7">
            <p className="eyebrow reveal mb-5">Tenant engagement, for UK social housing</p>
            <h1 className="h1 reveal" style={{ transitionDelay: '60ms' }}>
              Tenant engagement, done properly.
            </h1>
            <p className="mt-7 body-lg text-slate-800 font-medium max-w-[640px] reveal" style={{ transitionDelay: '120ms' }}>
              CX-Feedback is the tenant engagement platform built specifically for UK social housing. 110 social landlords already use it; 98% renew every year.
            </p>
            <div className="mt-9 flex flex-col sm:flex-row gap-3 sm:gap-4 reveal" style={{ transitionDelay: '180ms' }}>
              <BtnPrimary href="Book-a-call.html">Book a thirty-minute call</BtnPrimary>
              <BtnSecondary href="Product-surveys.html" icon={<IconArrowRight size={16} />}>See more about CX-Feedback</BtnSecondary>
            </div>
            <p className="mt-7 text-[15px] text-slate-700 flex items-center gap-2 reveal" style={{ transitionDelay: '240ms' }}>
              <IconPhoneCall size={16} className="text-slate-600" />
              Or call us directly on
              <a href="tel:+441418102599" className="font-bold text-slate-900 hover:text-blue-700">0141 810 2599</a>
              <span className="text-slate-600">— we answer the phone.</span>
            </p>
          </div>
          <div className="lg:col-span-5 reveal" style={{ transitionDelay: '200ms' }}>
            <div className="relative">
              <div className="absolute -inset-6 rounded-3xl bg-gradient-to-br from-blue-100 to-blue-50 -z-0" aria-hidden="true" />
              <div className="relative rounded-2xl border border-slate-200 bg-white shadow-cardlg overflow-hidden">
                <div className="px-5 py-3 border-b border-slate-200 flex items-center gap-2">
                  <span className="h-2.5 w-2.5 rounded-full bg-slate-300" />
                  <span className="h-2.5 w-2.5 rounded-full bg-slate-300" />
                  <span className="h-2.5 w-2.5 rounded-full bg-slate-300" />
                  <span className="ml-3 text-[12px] text-slate-500 font-medium">cxfb.co.uk/dashboard</span>
                </div>
                <div className="p-6 space-y-5">
                  <div>
                    <div className="text-[12px] uppercase tracking-wider font-semibold text-slate-500">TP01 satisfaction trend</div>
                    <div className="mt-3 flex items-end gap-2 h-24">
                      {[55, 62, 64, 70, 73, 78, 81].map((h, i) => (
                        <div key={i} className="flex-1 rounded-t-md bg-blue-600/80" style={{ height: `${h}%` }} />
                      ))}
                    </div>
                    <div className="mt-2 flex items-center justify-between text-[12px] text-slate-500">
                      <span>Jan</span><span>Jul</span>
                    </div>
                  </div>
                  <div className="grid grid-cols-3 gap-3 pt-2 border-t border-slate-100">
                    <Mini label="Sent" value="12,481" />
                    <Mini label="Open rate" value="71%" />
                    <Mini label="Response" value="34%" />
                  </div>
                  <div className="rounded-lg border border-slate-200 bg-slate-50 p-3 flex items-start gap-3">
                    <IconCheckCircle size={18} className="text-blue-600 mt-0.5" />
                    <div className="text-[13px] text-slate-700">
                      <strong className="font-semibold">412 tenants</strong> notified about Friday's planned works
                      <div className="text-slate-500">Targeted via map selection · 2 minutes ago</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

const Mini = ({ label, value }) => (
  <div>
    <div className="text-[12px] text-slate-500">{label}</div>
    <div className="text-[20px] font-bold text-slate-900 tabular-nums leading-tight">{value}</div>
  </div>
);

function TrustStrip() {
  const items = [
    { value: '110', label: 'UK social landlords' },
    { value: '1M+', label: 'Tenants reached every year' },
    { value: '98%', label: 'Renew every year' },
    { value: 'GDPR', label: 'UK compliant, EU-hosted' },
    { value: '2008', label: 'Trading since. Glasgow-based.' },
  ];
  return (
    <section
      className="relative bg-gradient-to-br from-slate-900 via-slate-900 to-slate-800 text-white border-t border-slate-800"
      aria-label="Trust signals"
    >
      <div className="max-w-container mx-auto px-5 sm:px-8 py-8 lg:py-10">
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 divide-y sm:divide-y-0 sm:divide-x divide-slate-700/70">
          {items.map((it, i) => (
            <div
              key={i}
              className="px-4 py-4 sm:py-2 flex flex-col items-center justify-start text-center"
            >
              <div className="text-[26px] sm:text-[30px] lg:text-[34px] font-extrabold tracking-tight text-white leading-none tabular-nums">
                {it.value}
              </div>
              <div className="mt-2 text-[12px] sm:text-[13px] font-medium uppercase tracking-wider text-slate-400 leading-snug">
                {it.label}
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function PainsSection() {
  const cards = [
    { Icon: IconBarChart, pain: 'We send surveys but never read the results properly.', answer: 'AI sentiment and triage reads every response, surfaces the urgent ones, and saves the team hundreds of hours.' },
    { Icon: IconSmartphone, pain: 'We cannot reach our under-35 tenants.', answer: 'Targeted SMS and email reach the digital-native cohort in seconds. The scrutiny panel is no longer the only voice in the room.' },
    { Icon: IconTarget, pain: 'One-size-fits-all communications are killing our response rates.', answer: 'Build a target group from any tenant attribute, then send only what is relevant. Mosscare St Vincents used this to move from C2 to C1.' },
    { Icon: IconPound, pain: 'Print, post and phone are eating the budget.', answer: 'Switching newsletters and consultations to SMS and email delivers a substantial saving the moment you turn it on. Blairtummock saw repairs response rates lift from 5% to 25%.' },
    { Icon: IconShieldAlert, pain: 'We dread an unannounced regulator inspection.', answer: 'The audit trail writes itself. Representation charts and the statement of representativeness come ready to hand to the regulator.' },
    { Icon: IconFileCheck, pain: 'We need to evidence the TIAA Standard, not just promise it.', answer: 'Ask, acknowledge, show the change. Three steps, one platform, every touch tracked against the tenant.' },
  ];
  return (
    <section className="py-20 lg:py-28 bg-white" aria-labelledby="pains-h">
      <div className="max-w-container mx-auto px-5 sm:px-8">
        <SectionHeading
          eyebrow="Sound familiar?"
          h2="The questions every engagement lead is fielding right now."
          intro="The engagement function has changed. The board wants the TP01 number. The regulator wants the evidence. The under-35 tenants will not answer a postal survey. The team is the same size it was three years ago."
          id="pains-h"
        />
        <div className="mt-14 grid md:grid-cols-2 lg:grid-cols-3 gap-6">
          {cards.map((c, i) => (
            <PainAnswerCard key={i} pain={c.pain} answer={c.answer} Icon={c.Icon} />
          ))}
        </div>
      </div>
    </section>
  );
}

function AchievementsGrid() {
  const tiles = [
    { value: '57% → 81%', label: 'TP07 "landlord keeps you informed", in a single year', source: 'Industrial Dwellings Society', href: 'Customers.html#ids' },
    { value: '+12%', label: 'TP07 lift since adopting Engagement+', source: 'Tuntum Housing Association', href: 'Customers.html#tuntum' },
    { value: '5% → 25%', label: 'Repairs satisfaction response rate', source: 'Blairtummock Housing Association', href: 'Customers.html#blairtummock' },
    { value: '78%', label: 'Of customers engaged in twelve months through targeted messaging', source: 'Muir Group Housing Association', href: 'Customers.html#muir' },
    { value: '10 mins', label: 'From incident to every affected tenant informed', source: 'Dacorum Borough Council', href: 'Customers.html#dacorum' },
    { value: 'C2 → C1', label: 'Consumer standards grading uplift', source: 'Mosscare St Vincents', href: 'Customers.html#msv' },
  ];
  return (
    <section className="py-20 lg:py-28 bg-blue-50 border-y border-blue-100" aria-labelledby="achieve-h">
      <div className="max-w-container mx-auto px-5 sm:px-8">
        <SectionHeading
          eyebrow="What becomes possible"
          h2="Real numbers from real landlords."
          intro="No averages, no rounded promises, no maybes. Every figure below is from a named customer."
          id="achieve-h"
        />
        <div className="mt-14 grid sm:grid-cols-2 lg:grid-cols-3 gap-6">
          {tiles.map((t, i) => (
            <StatTile key={i} value={t.value} label={t.label} source={t.source} href={t.href} />
          ))}
        </div>
      </div>
    </section>
  );
}

function ClosingTheLoopBlock() {
  return (
    <section className="py-20 lg:py-28 bg-white" aria-labelledby="loop-h">
      <div className="max-w-container mx-auto px-5 sm:px-8">
        <SectionHeading
          eyebrow="The defining use case"
          h2="Ask. Acknowledge. Show the change."
          intro={"Most landlords stop at 'ask'. They run the survey, log the data, write the board report, and move on. The tenant who answered hears nothing. Survey fatigue sets in. CX-Feedback closes the loop properly. Three steps, one platform, the audit trail the TIAA Standard expects, and the lift on TP01 every board paper opens with."}
          id="loop-h"
        />
        <ClosingTheLoopDiagram />
        <div className="mt-14 max-w-prose-wide mx-auto reveal">
          <QuoteCard
            accent
            quote="Partnering with CX-Feedback has been the single most important ingredient in our transformation journey in terms of customer communication and engagement."
            name="Charmaine Simei" role="CEO" org="Tuntum Housing Association"
            link="Customers.html#tuntum"
          />
        </div>
        <div className="mt-10 text-center reveal">
          <BtnSecondary href="Product-loop.html" icon={<IconArrowRight size={16} />}>Read the closing-the-loop guide</BtnSecondary>
        </div>
      </div>
    </section>
  );
}

function TwoFeaturesBlock() {
  return (
    <section className="py-20 lg:py-28 bg-slate-50 border-y border-slate-200" aria-labelledby="feats-h">
      <div className="max-w-container mx-auto px-5 sm:px-8">
        <SectionHeading
          eyebrow="The platform"
          h2="Two features. Hundreds of clever sub-features."
          intro="Surveys with targeting and reporting. Targeted SMS and email. Built for UK social housing, not retail, not banking, not generic. Hundreds of small things underneath, two big things on top."
          id="feats-h"
        />
        <div className="mt-14 grid lg:grid-cols-2 gap-6">
          <FeatureBig
            tag="Feature one"
            Icon={IconClipboard}
            title="Surveys, built for housing."
            body="Survey your tenants on any subject. Push the survey to exactly the right people in seconds. Turn the results into action and board-ready evidence in a few clicks."
            bullets={[
              'Trigger automatically from your housing management system the moment a repair, let, complaint or ASB case closes.',
              'Send by email, SMS, web form, phone, post, touchpoint or face to face — all managed in one place.',
              'Reports that print straight into your board pack and your regulator submission, scheduled to generate automatically.',
            ]}
            quote={{
              text: 'CX-Feedback and the E+ Module have enabled us to bring together the TSM and transactional surveys all in one place. The ability to engage with specific demographics and underrepresented customer groups has been invaluable.',
              name: 'Julie Clements', role: 'Data and Performance Manager', org: 'Regenda',
            }}
            href="Product-surveys.html"
          />
          <FeatureBig
            tag="Feature two"
            Icon={IconSend}
            title="The right tenant. The right message. The right moment."
            body="Build a beautiful, on-brand message and send it to exactly the right tenants by SMS or email in seconds. Because every message lands relevant, response rates stay high."
            bullets={[
              'Build a target group from any tenant attribute or by drawing a boundary on a map. Seconds, not days.',
              'Send pension credit information only to tenants of pension age. School-uniform support only to households with children. Incident updates only to the affected block.',
              'Track who received, opened, clicked and replied. The audit trail the regulator expects, written automatically.',
            ]}
            quote={{
              text: 'CX-Feedback has honestly changed my life this week regarding communicating with customers. The push messages have been incredibly helpful, easy, and stress-free.',
              name: 'Kirsty Rose', role: 'Marketing Communications Manager', org: 'Thrive Homes',
            }}
            href="Product-messaging.html"
          />
        </div>
      </div>
    </section>
  );
}

function FeatureBig({ tag, Icon, title, body, bullets, quote, href }) {
  return (
    <article className="rounded-2xl border border-slate-200 bg-white p-8 sm:p-10 reveal flex flex-col">
      <div className="flex items-center gap-3 mb-6">
        <span className="inline-flex h-11 w-11 items-center justify-center rounded-lg bg-blue-50 text-blue-600">
          <Icon size={22} />
        </span>
        <span className="text-[12px] uppercase tracking-wider font-semibold text-slate-500">{tag}</span>
      </div>
      <h3 className="text-[28px] sm:text-[32px] font-bold text-slate-900 tracking-tight leading-tight mb-4">{title}</h3>
      <p className="body-lg text-slate-600 mb-6">{body}</p>
      <ul className="space-y-3 mb-7">
        {bullets.map((b, i) => (
          <li key={i} className="flex items-start gap-3 text-[15px] text-slate-700 leading-relaxed">
            <IconCheck size={18} className="text-blue-600 mt-0.5 shrink-0" />
            <span>{b}</span>
          </li>
        ))}
      </ul>
      <figure className="rounded-lg bg-slate-50 border border-slate-200 p-5 mb-7">
        <blockquote className="text-[15px] text-slate-700 italic leading-relaxed">&ldquo;{quote.text}&rdquo;</blockquote>
        <figcaption className="mt-3 text-[13px] font-semibold text-slate-700">
          {quote.name}<span className="font-normal text-slate-500"> · {quote.role}, {quote.org}</span>
        </figcaption>
      </figure>
      <div className="mt-auto">
        <TextLinkCTA href={href}>See how this works</TextLinkCTA>
      </div>
    </article>
  );
}

function TeamSection() {
  return (
    <section className="py-20 lg:py-28 bg-white" aria-labelledby="team-h">
      <div className="max-w-container mx-auto px-5 sm:px-8">
        <div className="grid lg:grid-cols-2 gap-10 lg:gap-16 items-center">
          <div className="reveal">
            <div className="rounded-2xl overflow-hidden border border-slate-200 bg-slate-100">
              <ImagePlaceholder alt="The CX-Feedback team at the Glasgow office. Real photograph to be commissioned." ratio="4 / 3" tone="blue" />
            </div>
          </div>
          <div className="reveal" style={{ transitionDelay: '120ms' }}>
            <p className="eyebrow mb-4">The team behind the platform</p>
            <h2 id="team-h" className="h2 mb-6">The platform, plus the team you wish you had.</h2>
            <p className="body-lg text-slate-600 mb-5">
              When you sign with us, the software comes with the team. Unlimited access to our long-tenured British team. The best time of day to send a particular survey to get the highest response. Which question styles work for which tenant groups. How to phrase a sensitive question so tenants answer honestly. What other landlords have tried and what actually worked.
            </p>
            <p className="body-lg text-slate-600 mb-8">
              Eighteen years in social housing. On the phone. Included in every contract.
            </p>
            <BtnSecondary href="Team.html" icon={<IconArrowRight size={16} />}>Meet the team</BtnSecondary>
            <figure className="mt-10 pt-8 border-t border-slate-200">
              <blockquote className="text-[18px] italic text-slate-700 leading-relaxed">
                &ldquo;The system is intuitive and easy to navigate. Customer service from CX-Feedback has been excellent, with prompt and helpful support whenever needed.&rdquo;
              </blockquote>
              <figcaption className="mt-4 text-[14px] font-semibold text-slate-700">
                Gillian Bell<span className="font-normal text-slate-500"> · Blairtummock Housing Association</span>
              </figcaption>
            </figure>
          </div>
        </div>
      </div>
    </section>
  );
}

// Pre-calculated logo aspect ratios to prevent Layout Shifts (CLS) and enable visual weight balancing
const LOGO_ASPECTS = {
  "Accent.png": 1.32,
  "Albyn Housing Society.png": 1.53,
  "Almond Housing Association.png": 2.12,
  "Ardenglen Housing Association.png": 2.09,
  "Ark People Housing Care.png": 1.94,
  "Aspire Housing.png": 1.0,
  "Aster Group.png": 3.32,
  "Ayrshire Housing.png": 3.27,
  "Bernicia.png": 3.64,
  "Berwickshire Housing Association.png": 2.24,
  "Broadacres.png": 1.0,
  "Broadland Housing.png": 1.0,
  "Bury Council.png": 2.1,
  "Caledonia Housing Association.png": 1.5,
  "Calvay Housing Association.png": 3.75,
  "Castles and Coasts Housing Association.png": 2.18,
  "Cernach Housing Association.png": 1.21,
  "Cloch Housing Association.png": 1.08,
  "Clydesdale Housing Association.png": 3.59,
  "Cobalt Housing.png": 2.04,
  "Cromwood Housing Group.png": 2.08,
  "Cross Keys Homes.png": 0.9,
  "Dacorum Borough Council.png": 0.69,
  "Dunbritton Housing Association 30 Years.png": 1.21,
  "Dunbritton Housing Association.png": 1.0,
  "Elderpark Housing.png": 1.15,
  "Fairfield Housing Co-operative.png": 3.3,
  "Fife Council.png": 2.05,
  "Fife Housing Group.png": 1.07,
  "ForViva.png": 3.32,
  "Gateway Housing.png": 1.82,
  "Glen Oaks Housing Association.png": 5.13,
  "Golding Homes.png": 3.51,
  "Govan Housing Association.png": 2.75,
  "Govanhill Housing Association.png": 2.32,
  "Grampian Housing Association.png": 2.02,
  "Hammersmith and Fulham.png": 2.14,
  "Hexagon Housing.png": 3.4,
  "Highland Residential.png": 3.47,
  "Hillcrest.png": 2.01,
  "Hillhead Housing Association.png": 2.07,
  "Honeycomb Group.png": 1.53,
  "Industrial Dwellings Society.png": 1.0,
  "Kingdom Group.png": 1.69,
  "Legal and General Affordable Homes.png": 1.5,
  "Liberty.png": 3.54,
  "Link.png": 0.89,
  "Livin.png": 1.74,
  "Lochfield Park Housing Association.png": 3.5,
  "Maryhill Housing.png": 1.0,
  "Medway Council.png": 1.35,
  "Mid Devon District Council.png": 1.31,
  "Molendinar Park Housing Association.png": 2.8,
  "Muir Group.png": 1.11,
  "Muirhouse Housing Association.png": 3.62,
  "NG Homes.png": 0.75,
  "Northumberland County Council.png": 5.16,
  "Oak Tree Housing Association.png": 1.63,
  "Ochil View Housing Association.png": 1.79,
  "Paradigm Housing.png": 0.84,
  "Pineview Housing Association.png": 1.89,
  "Plus Dane Housing.png": 2.23,
  "Prima Group.png": 2.35,
  "Queens Cross Housing Association.png": 2.0,
  "Regenda Homes.png": 2.1,
  "Reidvale Housing Association.png": 1.36,
  "River Clyde Homes.png": 3.92,
  "Rooftop Housing Group.png": 4.06,
  "Rosebery Housing Association.png": 2.85,
  "Rural Stirling Housing Association.png": 1.35,
  "Rutherglen and Cambuslang Housing Association.png": 1.0,
  "Salix Homes.png": 2.74,
  "Salvation Army Homes.png": 4.09,
  "Saxon Weald.png": 1.88,
  "Scotland Map.png": 0.67,
  "Settle.png": 2.9,
  "Shire Housing.png": 1.41,
  "Six Town Housing.png": 1.9,
  "South Liverpool Homes.png": 1.51,
  "Southlakes Housing.png": 1.72,
  "Sparrow Shared Ownership.png": 1.0,
  "Squared.png": 2.99,
  "Stirling Council.png": 1.9,
  "Stockport Homes.png": 2.68,
  "The Scottish Government.png": 1.6,
  "The Wrekin Housing Group.png": 2.2,
  "Thrive Homes.png": 2.33,
  "Trust Housing Association.png": 2.6,
  "Wandle.png": 2.91,
  "Watford Community Housing.png": 1.45,
  "West Highland Housing Association.png": 1.35,
  "West Lothian Council.png": 2.38,
  "West Whitlawburn Housing Co-operative.png": 1.0,
  "Williamsburgh Housing Association.png": 1.7,
  "Wirral Methodist Housing Association.png": 2.33,
  "Worthing Homes.png": 1.91
};

// Aspect-ratio-based Tailwind class mapping to balance the visual weight of logos
function getLogoSizingClasses(file) {
  const aspect = LOGO_ASPECTS[file] || 1.8;

  if (aspect > 3.0) {
    // Extremely wide logo (e.g. Glen Oaks, Aster)
    // Wide box, large max width, maximum height, compact padding
    return {
      container: "min-w-[190px] max-w-[250px] px-6 h-20",
      image: "h-full max-h-12 sm:max-h-14 w-auto max-w-[180px]"
    };
  } else if (aspect > 2.0) {
    // Wide logo (e.g. Thrive, Settle)
    return {
      container: "min-w-[160px] max-w-[210px] px-5 h-20",
      image: "h-full max-h-12 sm:max-h-[50px] w-auto max-w-[150px]"
    };
  } else if (aspect >= 1.3) {
    // Standard landscape logo
    return {
      container: "min-w-[140px] max-w-[185px] px-5 h-20",
      image: "h-full max-h-12 sm:max-h-[50px] w-auto max-w-[125px]"
    };
  } else if (aspect >= 0.95) {
    // Square/compact logo
    // Scaled-down height to prevent overpowering, narrow snug card
    return {
      container: "min-w-[110px] max-w-[140px] px-4.5 h-20",
      image: "h-full max-h-10 sm:max-h-11 w-auto max-w-[95px]"
    };
  } else {
    // Tall/portrait logo
    // Custom tight frame and height to sit balanced
    return {
      container: "min-w-[100px] max-w-[130px] px-4 h-20",
      image: "h-full max-h-10 sm:max-h-[44px] w-auto max-w-[85px]"
    };
  }
}

function PartnerLogoTicker() {
  const fallbackLogos = [
    "Accent.png", "Albyn Housing Society.png", "Almond Housing Association.png", "Ardenglen Housing Association.png",
    "Ark People Housing Care.png", "Aspire Housing.png", "Aster Group.png", "Ayrshire Housing.png",
    "Bernicia.png", "Berwickshire Housing Association.png", "Broadacres.png", "Broadland Housing.png",
    "Bury Council.png", "Caledonia Housing Association.png", "Calvay Housing Association.png",
    "Castles and Coasts Housing Association.png", "Cernach Housing Association.png", "Cloch Housing Association.png",
    "Clydesdale Housing Association.png", "Cobalt Housing.png", "Cromwood Housing Group.png",
    "Cross Keys Homes.png", "Dacorum Borough Council.png", "Dunbritton Housing Association.png",
    "Dunbritton Housing Association 30 Years.png", "Elderpark Housing.png", "Fairfield Housing Co-operative.png",
    "Fife Council.png", "Fife Housing Group.png", "ForViva.png", "Gateway Housing.png",
    "Glen Oaks Housing Association.png", "Golding Homes.png", "Govan Housing Association.png",
    "Govanhill Housing Association.png", "Grampian Housing Association.png", "Hammersmith and Fulham.png",
    "Hexagon Housing.png", "Highland Residential.png", "Hillcrest.png", "Hillhead Housing Association.png",
    "Honeycomb Group.png", "Industrial Dwellings Society.png", "Kingdom Group.png",
    "Legal and General Affordable Homes.png", "Liberty.png", "Link.png", "Livin.png",
    "Lochfield Park Housing Association.png", "Maryhill Housing.png", "Medway Council.png",
    "Mid Devon District Council.png", "Molendinar Park Housing Association.png", "Muir Group.png",
    "Muirhouse Housing Association.png", "NG Homes.png", "Northumberland County Council.png",
    "Oak Tree Housing Association.png", "Ochil View Housing Association.png", "Paradigm Housing.png",
    "Pineview Housing Association.png", "Plus Dane Housing.png", "Prima Group.png",
    "Queens Cross Housing Association.png", "Regenda Homes.png", "Reidvale Housing Association.png",
    "River Clyde Homes.png", "Rooftop Housing Group.png", "Rosebery Housing Association.png",
    "Rural Stirling Housing Association.png", "Rutherglen and Cambuslang Housing Association.png",
    "Salix Homes.png", "Salvation Army Homes.png", "Saxon Weald.png",
    "Settle.png", "Shire Housing.png", "Six Town Housing.png", "South Liverpool Homes.png",
    "Southlakes Housing.png", "Sparrow Shared Ownership.png", "Squared.png", "Stirling Council.png",
    "Stockport Homes.png", "The Scottish Government.png", "The Wrekin Housing Group.png", "Thrive Homes.png",
    "Trust Housing Association.png", "Wandle.png", "Watford Community Housing.png",
    "West Highland Housing Association.png", "West Lothian Council.png", "West Whitlawburn Housing Co-operative.png",
    "Williamsburgh Housing Association.png", "Wirral Methodist Housing Association.png", "Worthing Homes.png"
  ];

  const [logoFiles, setLogoFiles] = React.useState(fallbackLogos);

  React.useEffect(() => {
    async function discoverLogos() {
      try {
        // Try dynamic PHP script first (works perfectly on XAMPP)
        const phpRes = await fetch('get-logos.php');
        if (phpRes.ok) {
          const files = await phpRes.json();
          if (Array.isArray(files) && files.length > 0) {
            setLogoFiles(files);
            return;
          }
        }
      } catch (e) {
        console.warn("PHP logo discovery failed, trying folder index...", e);
      }

      try {
        // Try dynamic directory listing fetch
        const dirRes = await fetch('assets/logos/');
        if (dirRes.ok) {
          const html = await dirRes.text();
          const parser = new DOMParser();
          const doc = parser.parseFromString(html, 'text/html');
          const links = Array.from(doc.querySelectorAll('a'));
          const files = links
            .map(link => link.getAttribute('href'))
            .filter(href => href && (href.toLowerCase().endsWith('.png') || href.toLowerCase().endsWith('.jpg') || href.toLowerCase().endsWith('.jpeg') || href.toLowerCase().endsWith('.svg') || href.toLowerCase().endsWith('.webp')))
            .map(href => decodeURIComponent(href.split('/').pop()))
            .filter((value, index, self) => self.indexOf(value) === index && value !== '.gitkeep');
          
          if (files.length > 0) {
            setLogoFiles(files);
            return;
          }
        }
      } catch (e) {
        console.warn("Logo folder discovery failed, falling back to static list...", e);
      }
    }
    discoverLogos();
  }, []);

  // Distribute the dynamic logos equally across three rows
  const rowLength = Math.ceil(logoFiles.length / 3);
  const row1 = logoFiles.slice(0, rowLength);
  const row2 = logoFiles.slice(rowLength, rowLength * 2);
  const row3 = logoFiles.slice(rowLength * 2);

  const renderLogo = (file, i) => {
    const name = file.replace('.png', '');
    const sizes = getLogoSizingClasses(file);
    return (
      <div 
        key={file + i} 
        className={`flex items-center justify-center bg-white border border-slate-100 rounded-2xl select-none ${sizes.container}`}
      >
        <img 
          src={`assets/logos/${file}`} 
          alt={`${name} Logo`} 
          className={`object-contain ${sizes.image}`} 
        />
      </div>
    );
  };

  return (
    <section className="py-8 bg-slate-50 border-b border-slate-200 overflow-hidden relative" aria-label="Our housing partners">
      {/* Dynamic Keyframes injected locally to keep index.html clean and modular */}
      <style dangerouslySetInnerHTML={{ __html: `
        @keyframes marquee-left {
          0% { transform: translate3d(0, 0, 0); }
          100% { transform: translate3d(-100%, 0, 0); }
        }
        @keyframes marquee-right {
          0% { transform: translate3d(-100%, 0, 0); }
          100% { transform: translate3d(0, 0, 0); }
        }
        .animate-marquee-left {
          display: flex;
          width: max-content;
          flex-shrink: 0;
          will-change: transform;
          animation: marquee-left 80s linear infinite;
        }
        .animate-marquee-right {
          display: flex;
          width: max-content;
          flex-shrink: 0;
          will-change: transform;
          animation: marquee-right 80s linear infinite;
        }
        .logo-mask {
          mask-image: linear-gradient(to right, transparent, black 15%, black 85%, transparent);
          -webkit-mask-image: linear-gradient(to right, transparent, black 15%, black 85%, transparent);
        }
      `}} />
      
      <div className="max-w-container mx-auto px-5 sm:px-8 mb-5 text-center">
        <p className="text-[12px] uppercase tracking-widest text-slate-400 font-extrabold">Trusted by 110+ UK Social Landlords</p>
      </div>

      <div className="space-y-3 relative w-full logo-mask">
        {/* Row 1: Left scrolling */}
        <div className="marquee-row overflow-hidden flex">
          <div className="animate-marquee-left gap-4 pr-4">
            {row1.map((item, i) => renderLogo(item, i))}
          </div>
          <div className="animate-marquee-left gap-4 pr-4" aria-hidden="true">
            {row1.map((item, i) => renderLogo(item, i + 'dup'))}
          </div>
        </div>

        {/* Row 2: Right scrolling */}
        <div className="marquee-row overflow-hidden flex">
          <div className="animate-marquee-right gap-4 pr-4">
            {row2.map((item, i) => renderLogo(item, i))}
          </div>
          <div className="animate-marquee-right gap-4 pr-4" aria-hidden="true">
            {row2.map((item, i) => renderLogo(item, i + 'dup'))}
          </div>
        </div>

        {/* Row 3: Left scrolling */}
        <div className="marquee-row overflow-hidden flex">
          <div className="animate-marquee-left gap-4 pr-4" style={{ animationDuration: '100s' }}>
            {row3.map((item, i) => renderLogo(item, i))}
          </div>
          <div className="animate-marquee-left gap-4 pr-4" aria-hidden="true" style={{ animationDuration: '100s' }}>
            {row3.map((item, i) => renderLogo(item, i + 'dup'))}
          </div>
        </div>
      </div>
    </section>
  );
}

function App() {
  useReveal();
  return (
    <>
      <Header />
      <main id="main">
        <div className="min-h-screen flex flex-col">
          <HomeHero />
          <PartnerLogoTicker />
          <TrustStrip />
        </div>
        <PainsSection />
        <AchievementsGrid />
        <ClosingTheLoopBlock />
        <TwoFeaturesBlock />
        <CustomerVoicesWall limit={6} />
        <CaseStudyShelf />
        <BuiltForHousingStrip />
        <TeamSection />
      </main>
      <Footer />
    </>
  );
}

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