// Hostelova landing — main app composition
const { useState, useEffect, useRef } = React;

// NAV + Footer now live in the shared site-chrome.jsx (reused by book.html).

// ---------- HERO ----------
const Hero = () => {
  const stageRef = useRef(null);
  const phoneRef = useRef(null);
  const stats = useHostelStats();
  useEffect(() => {
    const stage = stageRef.current;
    const phone = phoneRef.current;
    if (!stage || !phone) return;
    const onMove = (e) => {
      const r = stage.getBoundingClientRect();
      const x = (e.clientX - r.left) / r.width;
      const y = (e.clientY - r.top) / r.height;
      const ty = (x - 0.5) * 14; // -7 to 7 deg on Y
      const tx = -(y - 0.5) * 10; // -5 to 5 deg on X
      phone.style.setProperty("--tx", tx + "deg");
      phone.style.setProperty("--ty", ty + "deg");
    };
    const onLeave = () => {
      phone.style.setProperty("--tx", "0deg");
      phone.style.setProperty("--ty", "0deg");
    };
    stage.addEventListener("mousemove", onMove);
    stage.addEventListener("mouseleave", onLeave);
    return () => {
      stage.removeEventListener("mousemove", onMove);
      stage.removeEventListener("mouseleave", onLeave);
    };
  }, []);
  return (
  <section className="hero" id="top" data-screen-label="01 Hero">
    <div className="ambient a1"></div>
    <div className="ambient a2"></div>
    <div className="container hero-grid">
      <div className="hero-copy">
        <div className="eyebrow">
          <span className="dot"><Icon.Sparkle width="10" height="10" /></span>
          Trusted by students in Lucknow & beyond
          <span className="pulse"></span>
        </div>
        <h1>
          Hostelova
          <br />
          <span className="accent">find your stay.</span>
        </h1>
        <p className="sub">Find trusted hostels near your college.</p>
        <p className="desc">
          Discover verified hostels, compare rooms, check prices, view photos, and send booking inquiries — all from one simple app built for students.
        </p>
        <div className="hero-cta">
          <a className="btn btn-primary" href="book.html">
            <Icon.Sparkle width="14" height="14" /> Book a hostel online
          </a>
          <a className="btn btn-secondary" href="#download">
            <Icon.Download /> Download on Play Store
          </a>
        </div>
        <div className="hero-stats">
          <div className="hero-stat"><div className="num"><Counter key={`h-${stats.loaded}`} to={stats.hostels} suffix="+" /></div><div className="lbl">Verified hostels</div></div>
          <div className="hero-stat"><div className="num"><Counter key={`c-${stats.loaded}`} to={stats.cities} suffix="+" /></div><div className="lbl">Cities covered</div></div>
          <div className="hero-stat"><div className="num"><Counter key={`r-${stats.loaded}`} to={stats.rating} decimals={1} suffix="★" /></div><div className="lbl">Avg student rating</div></div>
        </div>
      </div>

      <div className="stage" ref={stageRef}>
        <div className="stage-floor"></div>
        <div className="floater f1">
          <span className="ico"><Icon.Verified width="16" height="16" /></span>
          <div className="meta"><span>Verified hostel</span><span className="sub">Owner ID checked</span></div>
        </div>
        <div className="floater f2">
          <span className="ico" style={{ background: "#fff3da", color: "#c87f00" }}><Icon.Pin width="16" height="16" /></span>
          <div className="meta"><span>Near you</span><span className="sub">Bakshi Ka Talab</span></div>
        </div>
        <div className="floater f3">
          <span className="ico" style={{ background: "#e6f7ee", color: "#16a34a" }}><Icon.Tag width="16" height="16" /></span>
          <div className="meta"><span>50% OFF</span><span className="sub">₹1,150/mo · was ₹2,300</span></div>
        </div>
        <div className="floater f4">
          <span className="ico" style={{ background: "#ffe9ec", color: "#e11d48" }}><Icon.Heart width="16" height="16" /></span>
          <div className="meta"><span>Saved favorites</span><span className="sub">3 hostels ready</span></div>
        </div>
        <div className="floater f5">
          <span className="ico" style={{ background: "#eef2ff", color: "#4f46e5" }}><Icon.Mail width="16" height="16" /></span>
          <div className="meta"><span>Booking inquiry sent</span><span className="sub">BK-0CDCAF · Pending</span></div>
        </div>

        <div className="phone-3d" ref={phoneRef}>
          <div className="phone-shadow"></div>
          <PhoneFrame><ScreenHome /></PhoneFrame>
        </div>
      </div>
    </div>
  </section>
  );
};

// ---------- FEATURE CARDS ----------
const FeatureCard = ({ I, num, title, desc, featured = false, span, children }) => (
  <div className={"feat-card" + (featured ? " featured" : "") + (span ? " span-" + span : "")}>
    <span className="corner-num">{num}</span>
    <div className="feat-ico">
      <I />
    </div>
    <h3 className="feat-title">{title}</h3>
    <p className="feat-desc">{desc}</p>
    {children && <div className="feat-vis">{children}</div>}
  </div>
);

const StudentsSection = () => (
  <section className="section-pad" id="students" data-screen-label="02 For Students">
    <div className="container">
      <div className="section-head">
        <span className="tag"><Icon.Users width="14" height="14" /> For Students</span>
        <h2>Everything you need to find the right hostel.</h2>
        <p>From searching nearby to sending a booking inquiry — Hostelova keeps every step simple, transparent, and student-friendly.</p>
      </div>
      <div className="feat-grid">
        <FeatureCard
          num="01" I={Icon.Pin}
          title="Search near you"
          desc="Find hostels by location, college name, or nearby area. Map view shows exactly how far each one is."
          span="4"
        >
          <div className="mini-row">
            <span className="mini-pill"><Icon.Pin width="11" height="11" style={{ marginRight: 4, verticalAlign: -1 }} />Koramangala</span>
            <span className="mini-pill">0.4 km</span>
          </div>
        </FeatureCard>

        <FeatureCard
          featured num="02" I={Icon.Verified}
          title="Verified hostel listings"
          desc="Every listing can show verified status, real photos, room details, and trust badges before you reach out."
          span="4"
        >
          <div className="mini-row">
            <span className="mini-pill">Owner ID</span>
            <span className="mini-pill">Real photos</span>
            <span className="mini-pill">Admin review</span>
          </div>
        </FeatureCard>

        <FeatureCard
          num="03" I={Icon.Bed}
          title="Compare room types"
          desc="Single, double, AC, non-AC and other options laid out with monthly prices and live availability."
          span="4"
        >
          <div className="mini-row">
            <span className="mini-pill">Single AC · ₹12.5k</span>
            <span className="mini-pill">Twin · ₹8.5k</span>
          </div>
        </FeatureCard>

        <FeatureCard
          num="04" I={Icon.Heart}
          title="Save favorites"
          desc="Bookmark hostels you like and come back when you're ready — no pressure, no premature inquiries."
          span="6"
        >
          <div style={{ display: "flex", gap: 6 }}>
            {["#ffd6a5", "#b8e0d2", "#c8d4ee"].map((c, i) => (
              <div key={i} style={{ width: 38, height: 38, borderRadius: 10, background: c, border: "2px solid white", boxShadow: "var(--shadow-sm)" }}></div>
            ))}
            <div style={{ width: 38, height: 38, borderRadius: 10, background: "var(--bg)", border: "1px dashed var(--line-2)", display: "grid", placeItems: "center", fontSize: 11, fontWeight: 700, color: "var(--muted)" }}>+2</div>
          </div>
        </FeatureCard>

        <FeatureCard
          num="05" I={Icon.Photo}
          title="Photos & full details"
          desc="Large image gallery, amenities, exact location, rating, reviews, and room-level information in one place."
          span="6"
        >
          <div className="mini-row">
            <span className="mini-pill">Gallery (18)</span>
            <span className="mini-pill">Reviews (84)</span>
            <span className="mini-pill">Amenities</span>
          </div>
        </FeatureCard>

        <FeatureCard
          num="06" I={Icon.Mail}
          title="Send inquiry or request booking"
          desc="Reach out without complicated steps — a short message, a few details, and the owner gets your request directly."
          span="6"
        >
          <div style={{ background: "var(--bg)", borderRadius: 10, padding: "10px 12px", fontSize: 12.5, color: "var(--ink-2)", fontFamily: "var(--font-mono)" }}>
            "Hi, is the Single AC room still available from May 1?"
          </div>
        </FeatureCard>

        <FeatureCard
          num="07" I={Icon.Bell}
          title="Notifications"
          desc="Important hostel updates, replies from owners, and booking or inquiry status alerts — never miss a beat."
          span="6"
        >
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            <div style={{ background: "var(--bg)", borderRadius: 8, padding: "8px 10px", fontSize: 12, color: "var(--ink-2)", display: "flex", justifyContent: "space-between" }}>
              <span>Owner replied to your inquiry</span><span style={{ color: "var(--muted-2)" }}>2m</span>
            </div>
            <div style={{ background: "var(--bg)", borderRadius: 8, padding: "8px 10px", fontSize: 12, color: "var(--ink-2)", display: "flex", justifyContent: "space-between" }}>
              <span>New hostel added near you</span><span style={{ color: "var(--muted-2)" }}>1h</span>
            </div>
          </div>
        </FeatureCard>
      </div>
    </div>
  </section>
);

// ---------- OWNER FEATURES ----------
const OwnersSection = () => (
  <section className="section-pad owners-section" id="owners" data-screen-label="03 For Owners">
    <div className="container">
      <div className="section-head">
        <span className="tag" style={{ background: "white", border: "1px solid var(--line)" }}><Icon.Building width="14" height="14" /> For Hostel Owners</span>
        <h2>List your hostel. Receive student inquiries.</h2>
        <p>Manage hostels, rooms, and student leads in one simple place — no complicated software, just the tools you actually need.</p>
      </div>
      <div className="feat-grid">
        <FeatureCard num="01" I={Icon.Building} title="Add & manage hostels"
          desc="Create listings with name, description, address, location, type, and photos. Edit anytime from your dashboard." span="4" />
        <FeatureCard num="02" I={Icon.Grid} title="Room setup"
          desc="Configure room types, prices, capacity, availability, and images so students see exactly what's on offer." span="4" />
        <FeatureCard num="03" I={Icon.Users} title="Student leads"
          desc="Receive booking requests and quick text inquiries from interested students, organised by hostel and date." span="4" featured />
        <FeatureCard num="04" I={Icon.Chart} title="Owner dashboard"
          desc="Track hostels, leads, inquiries, and notifications from a simple, focused dashboard built for daily use." span="6">
          <div className="mini-row">
            <span className="mini-pill">3 hostels</span>
            <span className="mini-pill">12 new leads</span>
            <span className="mini-pill">82% occupancy</span>
          </div>
        </FeatureCard>
        <FeatureCard num="05" I={Icon.Shield} title="Claim & verification flow"
          desc="Owners can claim imported listings, submit proof, and earn the verified badge after manual review." span="3" />
        <FeatureCard num="06" I={Icon.Megaphone} title="Send updates"
          desc="Push hostel alerts, room availability changes, or reminders directly to students who saved your listing." span="3" />
      </div>
    </div>
  </section>
);

// ---------- TRUST SECTION ----------
const TrustSection = () => {
  const items = [
    [Icon.Verified, "Verified hostel & owner flow", "Every owner goes through a verification step before listings go live, so students see real options."],
    [Icon.Photo, "Real photos & room details", "Listings use actual photos and room-level details — no stock images, no surprises."],
    [Icon.Tag, "Transparent monthly pricing", "Monthly rent shown upfront for every room type, with availability count next to it."],
    [Icon.Pin, "Location & nearby college info", "Distance to your college and nearby landmarks shown on every listing."],
    [Icon.Flag, "Report listing option", "Anything off? One tap to flag a listing for admin review."],
    [Icon.Eye, "Admin-reviewed ecosystem", "Listings, owners, and reported content all sit under a continuous admin review."],
    [Icon.Mail, "Student-first inquiry flow", "Inquiries stay simple, polite, and structured — no awkward DMs, no chasing owners across platforms."],
  ];
  return (
    <section className="section-pad trust-section" data-screen-label="04 Trust">
      <div className="container">
        <div className="section-head">
          <span className="tag"><Icon.Shield width="14" height="14" /> Trust & safety</span>
          <h2>Why Hostelova feels safer.</h2>
          <p>Booking a hostel from a stranger online shouldn't feel risky. Here's how we keep the ecosystem honest.</p>
        </div>
        <div className="trust-grid">
          {items.map(([I, t, d], i) => (
            <div key={i} className="trust-card">
              <div className="trust-ico"><I /></div>
              <div>
                <div className="trust-title">{t}</div>
                <div className="trust-desc" style={{ marginTop: 4 }}>{d}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// ---------- APP PREVIEW CAROUSEL ----------
const PreviewSection = () => {
  const screens = [
    { key: "login", label: "Login", Comp: ScreenLogin },
    { key: "home", label: "Home", Comp: ScreenHome },
    { key: "detail", label: "Hostel Detail", Comp: ScreenDetail },
    { key: "bookings", label: "My Bookings", Comp: ScreenBookings },
    { key: "owner", label: "Owner Dashboard", Comp: ScreenOwner },
    { key: "ohostels", label: "Your Hostels", Comp: ScreenOwnerHostels },
    { key: "oprofile", label: "Owner Profile", Comp: ScreenOwnerProfile },
  ];
  const [active, setActive] = useState(2); // center on detail
  const n = screens.length;

  const go = (dir) => setActive((a) => (a + dir + n) % n);

  const positions = screens.map((_, i) => {
    let offset = i - active;
    // wrap to shortest distance
    if (offset > n / 2) offset -= n;
    if (offset < -n / 2) offset += n;
    return offset;
  });

  return (
    <section className="section-pad preview-section" id="preview" data-screen-label="05 App Preview">
      <div className="container">
        <div className="section-head">
          <span className="tag"><Icon.Play width="12" height="12" /> Inside the app</span>
          <h2>Tap through the experience.</h2>
          <p>From search to inquiry to owner dashboard — here's every key screen of Hostelova.</p>
        </div>
        <div className="carousel-stage">
          {screens.map((s, i) => {
            const off = positions[i];
            const abs = Math.abs(off);
            const isCenter = off === 0;
            const visible = abs <= 2;
            const transform = `translateX(${off * 180}px) translateZ(${-abs * 180}px) rotateY(${off * -22}deg)`;
            const opacity = visible ? (1 - abs * 0.18) : 0;
            const zIndex = 10 - abs;
            return (
              <div
                key={s.key}
                className={"carousel-phone" + (isCenter ? " center" : "")}
                style={{ transform, opacity, zIndex, pointerEvents: visible ? "auto" : "none" }}
                onClick={() => setActive(i)}
              >
                <PhoneFrame><s.Comp /></PhoneFrame>
                <div className="phone-label">{s.label}</div>
              </div>
            );
          })}
          <div className="carousel-arrows">
            <div className="now-label" aria-live="polite">
              <span className="ix">{String(active + 1).padStart(2, "0")} / {String(n).padStart(2, "0")}</span>
            </div>
            <button className="carr" onClick={() => go(-1)} aria-label="Previous screen"><Icon.ArrowLeft /></button>
            <div className="carr dots" role="tablist" aria-label="App screens">
              {screens.map((s, i) => (
                <button
                  key={s.key}
                  className={"d" + (i === active ? " active" : "")}
                  onClick={() => setActive(i)}
                  aria-label={`Show ${s.label} screen`}
                  aria-selected={i === active}
                  title={s.label}
                  role="tab"
                ></button>
              ))}
            </div>
            <button className="carr" onClick={() => go(1)} aria-label="Next screen"><Icon.ArrowRight /></button>
          </div>
        </div>
      </div>
    </section>
  );
};

// ---------- FINAL CTA ----------
// 12x12 QR-like decorative pattern (placeholder)
const QrPattern = () => {
  const seed = "Hostelova-qr-2026-stable-seed";
  // deterministic pattern
  const cells = [];
  let h = 0;
  for (let i = 0; i < seed.length; i++) h = (h * 31 + seed.charCodeAt(i)) >>> 0;
  for (let i = 0; i < 144; i++) {
    h = (h * 1664525 + 1013904223) >>> 0;
    cells.push((h & 0xff) > 110);
  }
  // corner markers
  const corner = (r, c) => (r < 3 && c < 3) || (r < 3 && c > 8) || (r > 8 && c < 3);
  return (
    <div className="qr-square">
      {Array.from({ length: 144 }).map((_, i) => {
        const r = Math.floor(i / 12), c = i % 12;
        let filled = cells[i];
        if (corner(r, c)) {
          // 3x3 box marker frame
          const inR = r < 3 ? r : (r > 8 ? r - 9 : -1);
          const inC = c < 3 ? c : (c > 8 ? c - 9 : -1);
          if (inR === 0 || inR === 2 || inC === 0 || inC === 2) filled = true;
          else if (inR === 1 && inC === 1) filled = true;
          else filled = false;
        }
        return <span key={i} className={filled ? "" : "empty"}></span>;
      })}
    </div>
  );
};

// ---------- ABOUT US ----------
// Live stats (real counts from Supabase) for the About section.
const AboutStats = () => {
  const stats = useHostelStats();
  return (
    <div className="about-stats">
      <div className="as-item"><div className="as-num"><Counter key={`ah-${stats.loaded}`} to={stats.hostels} suffix="+" /></div><div className="as-lbl">Verified hostels</div></div>
      <div className="as-item"><div className="as-num"><Counter key={`ac-${stats.loaded}`} to={stats.cities} suffix="+" /></div><div className="as-lbl">Cities covered</div></div>
      <div className="as-item"><div className="as-num"><Counter key={`ar-${stats.loaded}`} to={stats.rating} decimals={1} suffix="★" /></div><div className="as-lbl">Avg rating</div></div>
    </div>
  );
};

const AboutSection = () => (
  <section className="about-section" id="about" data-screen-label="10 About">
    <div className="container">
      <div className="about-grid">
        <div className="about-copy">
          <span className="tag"><Icon.Sparkle width="13" height="13" /> About Hostelova</span>
          <h2>Built by students, for students.</h2>
          <p className="about-lead">
            Hostelova started with one question: why is finding a safe, verified hostel near your college still such a mess?
          </p>
          <p>
            We are a small team based out of Lucknow, building India's most trusted hostel-discovery platform for college students. Every feature in Hostelova exists for one reason — to remove the awkward calls, broker fees, fake listings, and last-minute surprises that students face when moving to a new city.
          </p>
          <p>
            Today we cover Lucknow and are expanding to other UP college towns, with verified hostels, transparent monthly pricing, and a clean in-app inquiry flow that respects both students and hostel owners.
          </p>
          <AboutStats />
          <div className="about-cta">
            <a href="pages/about.html" className="btn btn-primary">
              Read our full story <Icon.ArrowRight width="14" height="14" />
            </a>
          </div>
        </div>
        <div className="about-pillars">
          {[
            [Icon.Shield, "Trust first", "Owner verification, real photos, and admin-reviewed listings — built into the core of the product."],
            [Icon.Tag, "No hidden fees", "Monthly rent, deposit, and additional charges are shown upfront on every listing."],
            [Icon.Heart, "Student-friendly", "We don't sell student data, and we never run paid ranking — search results are honest."],
            [Icon.Mail, "Direct to owners", "One structured inquiry. No middlemen, no broker fees, no chasing across platforms."],
          ].map(([I, t, d], i) => (
            <div key={i} className="pillar">
              <div className="pillar-ico"><I /></div>
              <div>
                <div className="pillar-title">{t}</div>
                <div className="pillar-desc">{d}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  </section>
);

// ---------- CONTACT US ----------
const ContactSection = () => {
  const helpItems = [
    "Hostel listing issues",
    "Booking requests",
    "Account problems",
    "Report a hostel",
    "Verification support",
    "Business inquiries",
    "Advertisement & promotions",
  ];
  return (
    <section className="contact-section" id="contact" data-screen-label="11 Contact">
      <div className="container">
        <div className="section-head">
          <span className="tag"><Icon.Mail width="13" height="13" /> Contact Us</span>
          <h2>We're here to help.</h2>
          <p>We're here to help students and hostel owners with any questions, support requests, or listing-related issues.</p>
        </div>

        <div className="contact-grid contact-grid-3">
          <a href="mailto:hostelova.pvt.ltd@gmail.com" className="contact-card highlight">
            <div className="cc-ico"><Icon.Mail /></div>
            <div className="cc-label">Customer Support</div>
            <div className="cc-value cc-value-sm">hostelova.pvt.ltd@gmail.com</div>
            <div className="cc-meta">Email us anytime — we read every message.</div>
          </a>

          <div className="contact-card no-link">
            <div className="cc-ico"><Icon.Bell /></div>
            <div className="cc-label">Support Hours</div>
            <div className="cc-value">Monday – Saturday</div>
            <div className="cc-meta">10:00 AM – 7:00 PM (IST)</div>
          </div>

          <div className="contact-card no-link">
            <div className="cc-ico"><Icon.Chat /></div>
            <div className="cc-label">Response Time</div>
            <div className="cc-value">24 – 48 hours</div>
            <div className="cc-meta">Our team usually responds within 24–48 business hours.</div>
          </div>
        </div>

        <div className="contact-help-grid">
          <div className="help-card">
            <div className="help-head">
              <div className="cc-ico"><Icon.Sparkle /></div>
              <div>
                <div className="cc-label">Need help with?</div>
                <div className="help-title">Common topics we can support you on</div>
              </div>
            </div>
            <div className="help-list">
              {helpItems.map((t, i) => (
                <div key={i} className="help-item">
                  <span className="help-dot"><Icon.Check width="11" height="11" /></span>
                  <span>{t}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="help-card help-safety">
            <div className="help-head">
              <div className="cc-ico cc-ico-warn"><Icon.Shield /></div>
              <div>
                <div className="cc-label">Safety Notice</div>
                <div className="help-title">Keep your information safe</div>
              </div>
            </div>
            <p className="help-body">
              Please avoid sharing sensitive payment or personal information through email. Hostelova will never ask for your bank details, OTPs, or full passwords over email or chat.
            </p>
            <a href="mailto:hostelova.pvt.ltd@gmail.com" className="btn btn-primary help-cta">
              <Icon.Mail width="14" height="14" /> Email Customer Support
            </a>
          </div>
        </div>
      </div>
    </section>
  );
};

const FinalCTA = () => (
  <section className="cta-section" id="download" data-screen-label="06 Download">
    <div className="container">
      <div className="cta-card">
        <div>
          <h2>Ready to find your next hostel?</h2>
          <p>Download Hostelova and explore trusted hostels near your college — verified listings, real photos, and direct inquiries to owners.</p>
          <div className="cta-buttons">
            <a className="btn btn-primary" href="#"><Icon.Download /> Download on Play Store</a>
            <a className="btn btn-secondary" href="#preview"><Icon.Play width="14" height="14" /> Try App</a>
          </div>
        </div>
        <div className="cta-right">
          <div className="qr-card">
            <QrPattern />
            <div className="label">Scan to download<span className="small">play.google.com / hostelova</span></div>
          </div>
          <div className="play-badge">
            <Icon.Play width="28" height="28" />
            <div>
              <div className="top">GET IT ON</div>
              <div className="bot">Play Store</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>
);

// FOOTER now lives in the shared site-chrome.jsx (reused by book.html).

// ---------- APP ----------
const App = () => {
  const [theme, setTheme] = useTheme();

  // reveal-on-scroll
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver(
      (entries) => entries.forEach((e) => e.isIntersecting && e.target.classList.add("in")),
      { threshold: 0.15 }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);

  return (
    <>
      <ScrollProgress />
      <Nav theme={theme} setTheme={setTheme} />
      <Hero />
      <StudentsSection />
      <SearchDemo />
      <OwnersSection />
      <CompareSection />
      <TrustSection />
      <PreviewSection />
      <TestimonialsSection />
      <AboutSection />
      <FAQSection />
      <ContactSection />
      <FinalCTA />
      <Footer />
      <FloatBar />
    </>
  );
};

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
