// DrivOver — complete vehicle care in Chadoora, Budgam (Kashmir)
// Mobile-first responsive site — cars, SUVs, bikes, all welcome.

const { useState, useEffect, useRef } = React;

// ============ TWEAKABLE DEFAULTS ============
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "saffron",
  "heroVariant": "imageRight",
  "showFloatingCTAs": true
}/*EDITMODE-END*/;

const ACCENTS = {
  saffron: { hex: "#e0a44a", soft: "rgba(224,164,74,0.16)", glow: "rgba(224,164,74,0.35)", name: "Saffron Gold" },
  steel:   { hex: "#9aa3b2", soft: "rgba(154,163,178,0.18)", glow: "rgba(154,163,178,0.4)", name: "Steel Silver" },
  ice:     { hex: "#5aa9e6", soft: "rgba(90,169,230,0.16)", glow: "rgba(90,169,230,0.4)", name: "Ice Blue" },
};

// ============ STORAGE (localStorage — swap for backend later) ============
const LS = {
  reviews: "drivover.reviews",
  submissions: "drivover.submissions",
  gallery: "drivover.gallery",
  admin: "drivover.admin.session",
};

const SEED_REVIEWS = [
  { id: "s1", name: "Sameer K.", area: "Chadoora", text: "Got my Creta cleaned the week they opened. Foam wash, vacuum — honestly thorough. Even called next day to check.", rating: 5, ts: Date.now() - 1000*60*60*24*3 },
  { id: "s2", name: "Iqra J.", area: "Budgam", text: "Booked through WhatsApp, they picked up my Swift from home and dropped it back washed. Game-changer in winter.", rating: 5, ts: Date.now() - 1000*60*60*24*8 },
  { id: "s3", name: "Faisal R.", area: "Hyderpora", text: "Honest pricing, no upselling. The boys finished before time — first impression: 10/10.", rating: 5, ts: Date.now() - 1000*60*60*24*14 },
  { id: "s4", name: "Aasif M.", area: "Kralpora", text: "Local guys, sharp work. New shop but they know what they're doing. My Alto looks brand new.", rating: 5, ts: Date.now() - 1000*60*60*24*20 },
  { id: "s5", name: "Mehak A.", area: "Bemina", text: "Friendly team, decent prices. Interior detail was good — will come again.", rating: 4, ts: Date.now() - 1000*60*60*24*25 },
];

function loadReviews() {
  try {
    const arr = JSON.parse(localStorage.getItem(LS.reviews) || "null");
    if (Array.isArray(arr)) return arr.slice().sort((a,b) => b.ts - a.ts);
  } catch (e) {}
  // first run
  try { localStorage.setItem(LS.reviews, JSON.stringify(SEED_REVIEWS)); } catch(e){}
  return SEED_REVIEWS.slice().sort((a,b) => b.ts - a.ts);
}
function saveReview(r) {
  const cur = loadReviews();
  const next = [{ ...r, id: "r" + Date.now(), ts: Date.now() }, ...cur];
  try { localStorage.setItem(LS.reviews, JSON.stringify(next)); } catch(e){}
  window.dispatchEvent(new Event("drivover:reviews"));
}
function saveSubmission(s) {
  try {
    const cur = JSON.parse(localStorage.getItem(LS.submissions) || "[]");
    cur.unshift({ ...s, id: "sub" + Date.now(), ts: Date.now() });
    localStorage.setItem(LS.submissions, JSON.stringify(cur));
  } catch (e) {}
}

// ============ DATA ============
const SERVICES = [
  { id: "wash", name: "Body Wash", desc: "A quick, careful rinse and shampoo for any vehicle. Out the door shining.", price: "₹ 299", time: "30 min", soon: false },
  { id: "foam", name: "Foam Wash", desc: "Thick snow-foam bath that lifts dust without touching the paint — cars, SUVs, bikes.", price: "₹ 499", time: "45 min", soon: false },
  { id: "interior", name: "Interior Cleaning", desc: "Dashboard, seats, doors — wiped, conditioned, and fresh again.", price: "₹ 699", time: "1 hr", soon: false },
  { id: "vacuum", name: "Vacuum Cleaning", desc: "Every corner, mat, and crevice. We take the dust seriously.", price: "₹ 249", time: "20 min", soon: false },
  { id: "wax", name: "Wax Polish", desc: "Hand-applied polish that brings the shine back to old paint.", price: "₹ 999", time: "1.5 hr", soon: false },
  { id: "tire", name: "Wheel & Tire Care", desc: "Black, glossy tires. Clean rims. Like the day you bought it.", price: "₹ 199", time: "15 min", soon: false },
  { id: "pickup", name: "Pickup & Drop", desc: "Can't drive in? We'll pick up from your home or office, wash it, and drop it back. Free within 3 km of Chadoora.", price: "Free", time: "3 km radius", soon: false },
  { id: "ceramic", name: "Ceramic Coating", desc: "9H-grade protection. Years of shine, less washing.", price: "Coming soon", time: "", soon: true },
  { id: "ppf", name: "Paint Protection Film", desc: "Invisible shield against stones, scratches, and Kashmir winters.", price: "Coming soon", time: "", soon: true },
  { id: "graphene", name: "Graphene Coating", desc: "The next step after ceramic. Hydrophobic, slick, durable.", price: "Coming soon", time: "", soon: true },
];

const NAV_LINKS = [
  { id: "services", label: "Services" },
  { id: "about", label: "About" },
  { id: "gallery", label: "Gallery" },
  { id: "location", label: "Visit" },
  { id: "contact", label: "Book" },
];

const GALLERY = [
  { id: 1, label: "Foam wash · sedan", tall: false, tone: "#1a1a1f" },
  { id: 2, label: "Interior detail", tall: true, tone: "#16161a" },
  { id: 3, label: "Wax polish glow", tall: false, tone: "#1c1c22" },
  { id: 4, label: "Wheel cleanup", tall: false, tone: "#17171c" },
  { id: 5, label: "Night shine", tall: true, tone: "#0e0e12" },
  { id: 6, label: "Before / after", tall: false, tone: "#1a1a20" },
  { id: 7, label: "SUV foam bath", tall: false, tone: "#15151a" },
  { id: 8, label: "Dashboard finish", tall: false, tone: "#1b1b21" },
];

// ============ LOGO ============
function DrivOverMark({ size = 28, accent = "#e0a44a", animate = true }) {
  // A stylized chinar leaf above a Pir Panjal silhouette — the "O" in DrivOver
  return (
    <svg width={size} height={size} viewBox="0 0 40 40" className={"dz-mark" + (animate ? " dz-mark--anim" : "")}>
      <defs>
        <linearGradient id="dzg" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor={accent} stopOpacity="0.95" />
          <stop offset="100%" stopColor={accent} stopOpacity="0.55" />
        </linearGradient>
      </defs>
      {/* mountain — Pir Panjal silhouette */}
      <path d="M 4 30 L 14 18 L 20 24 L 28 14 L 36 30 Z" fill="url(#dzg)" opacity="0.85" />
      {/* chinar leaf */}
      <g className="dz-leaf" style={{ transformOrigin: "20px 12px" }}>
        <path
          d="M 20 4 C 17 7 16 9 17 12 C 14 11 12 11 11 13 C 13 14 15 15 17 14 C 16 16 15 18 17 19 L 20 16 L 23 19 C 25 18 24 16 23 14 C 25 15 27 14 29 13 C 28 11 26 11 23 12 C 24 9 23 7 20 4 Z"
          fill={accent}
        />
        <line x1="20" y1="6" x2="20" y2="17" stroke="#0a0a0b" strokeWidth="0.6" opacity="0.4" />
      </g>
    </svg>
  );
}

function Wordmark({ accent }) {
  return (
    <div className="wordmark">
      <DrivOverMark accent={accent} />
      <span className="wordmark__text">
        Driv<span style={{ color: accent }}>O</span>ver
      </span>
    </div>
  );
}

// ============ NAV ============
function Nav({ accent, onBook }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const goTo = (id) => {
    setOpen(false);
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
  };
  return (
    <header className={"nav" + (scrolled ? " nav--scrolled" : "")}>
      <div className="nav__inner">
        <button className="nav__brand" onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}>
          <Wordmark accent={accent} />
        </button>
        <nav className="nav__links">
          {NAV_LINKS.map((l) => (
            <button key={l.id} onClick={() => goTo(l.id)} className="nav__link">
              {l.label}
            </button>
          ))}
        </nav>
        <button className="btn btn--accent nav__cta" onClick={onBook}>
          Book now
        </button>
        <button className="nav__burger" onClick={() => setOpen(!open)} aria-label="Menu">
          <span></span>
          <span></span>
          <span></span>
        </button>
      </div>
      {open && (
        <div className="nav__drawer">
          {NAV_LINKS.map((l) => (
            <button key={l.id} onClick={() => goTo(l.id)} className="nav__drawer-link">
              {l.label}
            </button>
          ))}
          <button className="btn btn--accent nav__drawer-cta" onClick={() => { setOpen(false); onBook(); }}>
            Book now →
          </button>
        </div>
      )}
    </header>
  );
}

// ============ HERO ============
function Hero({ accent, variant, onBook }) {
  return (
    <section className={"hero hero--" + variant}>
      <div className="hero__bg">
        <div className="hero__bg-gradient" />
        <div className="hero__bg-glow" style={{ background: `radial-gradient(circle at 70% 40%, ${ACCENTS_RUNTIME().glow}, transparent 60%)` }} />
        <CarPlaceholder accent={accent} />
      </div>
      <div className="hero__content">
        <div className="hero__eyebrow">
          <span className="dot" style={{ background: accent }}></span>
          Chadoora · Budgam, Kashmir
        </div>
        <h1 className="hero__title">
          Complete care,<br />
          <em>under one roof.</em>
        </h1>
        <p className="hero__sub">
          A neighbourhood studio on Batpur–Kralpora Road for every vehicle in the valley — cars, SUVs, bikes. Foam, wax, vacuum, and a finish you can see your face in.
        </p>
        <div className="hero__ctas">
          <button className="btn btn--accent" onClick={onBook}>
            Book a wash
            <svg width="16" height="16" viewBox="0 0 16 16"><path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </button>
          <button className="btn btn--ghost" onClick={() => document.getElementById("location").scrollIntoView({ behavior: "smooth" })}>
            <svg width="16" height="16" viewBox="0 0 16 16"><path d="M8 14s5-4.5 5-8.5a5 5 0 0 0-10 0C3 9.5 8 14 8 14z" stroke="currentColor" strokeWidth="1.4" fill="none"/><circle cx="8" cy="5.5" r="1.6" stroke="currentColor" strokeWidth="1.4" fill="none"/></svg>
            Get directions
          </button>
        </div>
        <div className="hero__stats">
          <div className="hero__stat"><b>25+</b><span>vehicles cared for</span></div>
          <div className="hero__stat"><b>1 month</b><span>fresh in Chadoora</span></div>
          <div className="hero__stat"><b>Free</b><span>pickup &amp; drop nearby</span></div>
        </div>
      </div>
      <div className="hero__scroll">
        <span>Scroll</span>
        <span className="hero__scroll-line"></span>
      </div>
    </section>
  );
}

// Tiny helper so we can read CSS var glow inside inline styles
function ACCENTS_RUNTIME() {
  if (typeof document === "undefined") return { glow: "rgba(224,164,74,0.35)" };
  const v = getComputedStyle(document.documentElement).getPropertyValue("--accent-glow").trim();
  return { glow: v || "rgba(224,164,74,0.35)" };
}

// Stylized car placeholder — silhouette inside a striped frame
function CarPlaceholder({ accent }) {
  return (
    <div className="car-placeholder" aria-hidden>
      <svg viewBox="0 0 600 280" preserveAspectRatio="xMidYMid meet" className="car-placeholder__svg">
        <defs>
          <linearGradient id="bodyG" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#26262d" />
            <stop offset="50%" stopColor="#15151a" />
            <stop offset="100%" stopColor="#0c0c10" />
          </linearGradient>
          <linearGradient id="shineG" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0%" stopColor={accent} stopOpacity="0" />
            <stop offset="50%" stopColor={accent} stopOpacity="0.5" />
            <stop offset="100%" stopColor={accent} stopOpacity="0" />
          </linearGradient>
        </defs>
        {/* ground reflection */}
        <ellipse cx="300" cy="240" rx="240" ry="14" fill="#000" opacity="0.55" />
        {/* car body */}
        <path
          d="M 70 200 Q 90 180 130 170 L 180 130 Q 210 110 260 108 L 360 108 Q 410 110 440 130 L 490 170 Q 520 175 540 200 L 540 220 Q 540 232 525 232 L 100 232 Q 70 232 70 218 Z"
          fill="url(#bodyG)"
          stroke="#2a2a32"
          strokeWidth="1"
        />
        {/* windows */}
        <path d="M 195 168 L 220 130 Q 240 118 270 116 L 360 116 Q 395 118 415 132 L 440 168 Z" fill="#0a0a0e" opacity="0.85" />
        <line x1="305" y1="118" x2="305" y2="168" stroke="#0a0a0b" strokeWidth="1" opacity="0.6" />
        {/* shine */}
        <path d="M 80 195 Q 300 175 530 195" stroke="url(#shineG)" strokeWidth="2" fill="none" />
        {/* wheels */}
        <circle cx="170" cy="232" r="26" fill="#0a0a0b" stroke="#2a2a32" />
        <circle cx="170" cy="232" r="14" fill="#1a1a20" />
        <circle cx="170" cy="232" r="4" fill={accent} opacity="0.7" />
        <circle cx="445" cy="232" r="26" fill="#0a0a0b" stroke="#2a2a32" />
        <circle cx="445" cy="232" r="14" fill="#1a1a20" />
        <circle cx="445" cy="232" r="4" fill={accent} opacity="0.7" />
        {/* headlight */}
        <path d="M 530 188 Q 540 192 540 200 L 530 202 Z" fill={accent} opacity="0.8" />
      </svg>
      <div className="car-placeholder__label">drop hero car photo here</div>
    </div>
  );
}

// ============ SERVICES ============
function Services({ accent, onBook }) {
  const active = SERVICES.filter((s) => !s.soon);
  const soon = SERVICES.filter((s) => s.soon);
  return (
    <section id="services" className="section">
      <SectionHead
        eyebrow="What we do"
        title={<>Everything your ride<br/>could need, in one place.</>}
        sub="Honest pricing. No upsell theatre. Pay only for what your vehicle needs today."
      />
      <div className="services">
        {active.map((s) => (
          <ServiceCard key={s.id} s={s} accent={accent} onBook={onBook} />
        ))}
      </div>

      <div className="services__soon-header">
        <span className="services__soon-eyebrow" style={{ color: accent }}>Coming soon</span>
        <h3>Premium protection, on the way.</h3>
      </div>
      <div className="services services--soon">
        {soon.map((s) => (
          <ServiceCard key={s.id} s={s} accent={accent} />
        ))}
      </div>
    </section>
  );
}

function ServiceCard({ s, accent, onBook }) {
  return (
    <article className={"service" + (s.soon ? " service--soon" : "")}>
      <div className="service__icon">
        <ServiceIcon id={s.id} accent={accent} />
      </div>
      <div className="service__body">
        <div className="service__head">
          <h4>{s.name}</h4>
          {s.soon && <span className="service__badge">Soon</span>}
        </div>
        <p>{s.desc}</p>
        <div className="service__foot">
          <div>
            <span className="service__price-label">From</span>
            <span className="service__price">{s.price}</span>
            {s.time && <span className="service__time"> · {s.time}</span>}
          </div>
          {!s.soon && (
            <button className="service__cta" onClick={onBook} aria-label={"Book " + s.name}>
              <svg width="14" height="14" viewBox="0 0 16 16"><path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </button>
          )}
        </div>
      </div>
    </article>
  );
}

function ServiceIcon({ id, accent }) {
  const stroke = { stroke: accent, strokeWidth: 1.4, fill: "none", strokeLinecap: "round", strokeLinejoin: "round" };
  switch (id) {
    case "wash":
      return <svg viewBox="0 0 24 24"><path d="M5 14 L7 9 L17 9 L19 14 L19 18 L5 18 Z" {...stroke}/><circle cx="8.5" cy="18" r="1.6" {...stroke}/><circle cx="15.5" cy="18" r="1.6" {...stroke}/><path d="M4 6 Q4 4 5 4 M8 6 Q8 4 9 4 M12 6 Q12 4 13 4" {...stroke}/></svg>;
    case "foam":
      return <svg viewBox="0 0 24 24"><circle cx="8" cy="9" r="2.5" {...stroke}/><circle cx="14" cy="7" r="2" {...stroke}/><circle cx="17" cy="11" r="1.5" {...stroke}/><circle cx="11" cy="13" r="1.8" {...stroke}/><path d="M5 18 L19 18" {...stroke}/></svg>;
    case "interior":
      return <svg viewBox="0 0 24 24"><path d="M6 18 L6 11 Q6 8 9 8 L15 8 Q18 8 18 11 L18 18" {...stroke}/><path d="M6 13 L18 13" {...stroke}/><rect x="9" y="11" width="6" height="0.5" {...stroke}/></svg>;
    case "vacuum":
      return <svg viewBox="0 0 24 24"><path d="M4 18 L4 14 Q4 11 7 11 L11 11" {...stroke}/><rect x="11" y="9" width="9" height="6" rx="1.5" {...stroke}/><circle cx="6" cy="18" r="1.6" {...stroke}/></svg>;
    case "wax":
      return <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="6" {...stroke}/><path d="M9 10 Q11 8 13 10" {...stroke}/><circle cx="10" cy="11" r="0.6" fill={accent}/></svg>;
    case "tire":
      return <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="7" {...stroke}/><circle cx="12" cy="12" r="3" {...stroke}/><path d="M12 5 L12 9 M12 15 L12 19 M5 12 L9 12 M15 12 L19 12" {...stroke}/></svg>;
    case "pickup":
      return <svg viewBox="0 0 24 24"><path d="M3 16 L3 12 L7 8 L14 8 L17 12 L21 12 L21 16" {...stroke}/><circle cx="8" cy="16" r="1.6" {...stroke}/><circle cx="17" cy="16" r="1.6" {...stroke}/><path d="M14 4 L14 8 M11 6 L17 6" {...stroke}/></svg>;
    case "ceramic":
      return <svg viewBox="0 0 24 24"><path d="M12 4 L19 8 L19 15 Q19 18 12 20 Q5 18 5 15 L5 8 Z" {...stroke}/><path d="M9 12 L11 14 L15 10" {...stroke}/></svg>;
    case "ppf":
      return <svg viewBox="0 0 24 24"><path d="M5 6 L19 6 L19 16 Q19 18 17 18 L7 18 Q5 18 5 16 Z" {...stroke}/><path d="M5 6 Q12 9 19 6" {...stroke}/></svg>;
    case "graphene":
      return <svg viewBox="0 0 24 24"><path d="M12 5 L17 8 L17 14 L12 17 L7 14 L7 8 Z" {...stroke}/><path d="M12 5 L12 17 M7 8 L17 14 M17 8 L7 14" {...stroke}/></svg>;
    default:
      return null;
  }
}

// ============ ABOUT ============
function About({ accent }) {
  const points = [
    { t: "Brand-new in Chadoora", d: "We opened on Batpur–Kralpora Road just a month ago. Small team, big plans." },
    { t: "Pickup & drop, free", d: "Can't drive in? We'll fetch your vehicle and bring it back washed — free within 3 km." },
    { t: "Proper products", d: "pH-neutral shampoos, soft microfibres — nothing that eats your paint." },
    { t: "Honest prices", d: "Pay for what your vehicle needs. We'll never sell you a coating it doesn't." },
  ];
  return (
    <section id="about" className="section about">
      <div className="about__col about__col--text">
        <span className="eyebrow">About DrivOver</span>
        <h2 className="h2">
          Born from a love of clean rides<br/>
          and Kashmiri hospitality.
        </h2>
        <p className="lead">
          We opened our first bay in Chadoora a month ago, on Batpur–Kralpora Road. Twenty-five vehicles in and counting. Cars, SUVs, bikes — we treat your ride like our own.
        </p>
        <ul className="about__list">
          {points.map((p) => (
            <li key={p.t}>
              <span className="about__dot" style={{ background: accent }}></span>
              <div>
                <b>{p.t}</b>
                <span>{p.d}</span>
              </div>
            </li>
          ))}
        </ul>
      </div>
      <div className="about__col about__col--media">
        <div className="about__photo">
          <div className="about__photo-label">team at work · placeholder</div>
        </div>
        <div className="about__quote">
          <p>"Cleanest my car has ever been. They even got the chinar leaves out of the boot."</p>
          <span>— Aamir, Budgam</span>
        </div>
      </div>
    </section>
  );
}

// ============ GALLERY ============
function loadGallery() {
  try {
    const uploads = JSON.parse(localStorage.getItem(LS.gallery) || "[]");
    return [...uploads, ...GALLERY];
  } catch (e) { return GALLERY; }
}

function Gallery({ accent }) {
  const [open, setOpen] = useState(null);
  const [items, setItems] = useState(loadGallery);
  useEffect(() => {
    const onUpdate = () => setItems(loadGallery());
    window.addEventListener("drivover:gallery", onUpdate);
    return () => window.removeEventListener("drivover:gallery", onUpdate);
  }, []);
  return (
    <section id="gallery" className="section">
      <SectionHead
        eyebrow="The work"
        title={<>Before, after, and the shine in between.</>}
        sub="Tap any photo to see it bigger."
      />
      <div className="gallery">
        {items.map((g, i) => (
          <button
            key={g.id}
            className={"gallery__item" + (g.tall ? " gallery__item--tall" : "")}
            onClick={() => setOpen(i)}
            style={{ background: g.src ? "#000" : g.tone }}
          >
            {g.src ? (
              <img src={g.src} alt={g.label || "Gallery photo"} className="gallery__img" />
            ) : (
              <span className="gallery__placeholder">{g.label}</span>
            )}
            <span className="gallery__zoom" style={{ borderColor: accent, color: accent }}>+</span>
          </button>
        ))}
      </div>
      {open !== null && (
        <Lightbox
          items={items}
          index={open}
          onClose={() => setOpen(null)}
          onIndex={setOpen}
          accent={accent}
        />
      )}
    </section>
  );
}

function Lightbox({ items, index, onClose, onIndex, accent }) {
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
      if (e.key === "ArrowRight") onIndex((index + 1) % items.length);
      if (e.key === "ArrowLeft") onIndex((index - 1 + items.length) % items.length);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [index]);
  const g = items[index];
  return (
    <div className="lightbox" onClick={onClose}>
      <button className="lightbox__close" onClick={onClose} aria-label="Close">×</button>
      <button className="lightbox__nav lightbox__nav--prev" onClick={(e) => { e.stopPropagation(); onIndex((index - 1 + items.length) % items.length); }}>‹</button>
      <div className="lightbox__frame" onClick={(e) => e.stopPropagation()} style={{ background: g.src ? "#000" : g.tone }}>
        {g.src ? (
          <img src={g.src} alt={g.label || ""} className="lightbox__img" />
        ) : (
          <span className="lightbox__label">{g.label}</span>
        )}
        <span className="lightbox__count" style={{ color: accent }}>{index + 1} / {items.length}</span>
      </div>
      <button className="lightbox__nav lightbox__nav--next" onClick={(e) => { e.stopPropagation(); onIndex((index + 1) % items.length); }}>›</button>
    </div>
  );
}

// ============ LOCATION ============
function Location({ accent }) {
  return (
    <section id="location" className="section location">
      <div className="location__map">
        <MapPlaceholder accent={accent} />
        <div className="location__pin" style={{ borderColor: accent }}>
          <span style={{ background: accent }} className="location__pin-dot"></span>
        </div>
      </div>
      <div className="location__info">
        <span className="eyebrow">Find us</span>
        <h2 className="h2">Chadoora, Budgam.<br/>Right on Kralpora Road.</h2>
        <div className="location__address">
          <b>DrivOver Detailing Studio</b><br/>
          Check Chadura, Batpur,<br/>
          Kralpora Road, Chadoora<br/>
          Budgam 191113, J&amp;K
        </div>
        <div className="location__hours">
          <h5>Open hours</h5>
          <div className="location__hours-row"><span>Mon — Sat</span><b>9:00 — 8:00</b></div>
          <div className="location__hours-row"><span>Sunday</span><b>10:00 — 4:00</b></div>
          <div className="location__hours-row"><span>Fridays · 1—2pm</span><b>Closed (Jumma)</b></div>
        </div>
        <div className="location__ctas">
          <a className="btn btn--accent" href="#contact" onClick={(e) => { e.preventDefault(); document.getElementById("contact").scrollIntoView({ behavior: "smooth" }); }}>
            Get directions
          </a>
          <a className="btn btn--ghost" href="#" onClick={(e) => e.preventDefault()}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M20 4 C 18 2 15 1 12 1 C 6 1 1 6 1 12 C 1 14 1.5 16 2.5 17.5 L 1 23 L 6.5 21.5 C 8 22.5 10 23 12 23 C 18 23 23 18 23 12 C 23 9 22 6 20 4 Z M 12 21 C 10.5 21 9 20.5 7.5 19.5 L 3.5 21 L 5 17 C 4 15.5 3.5 14 3.5 12 C 3.5 7 7 3.5 12 3.5 C 17 3.5 20.5 7 20.5 12 C 20.5 17 17 21 12 21 Z"/></svg>
            WhatsApp us
          </a>
        </div>
      </div>
    </section>
  );
}

function MapPlaceholder({ accent }) {
  return (
    <svg viewBox="0 0 400 400" className="mapsvg" preserveAspectRatio="xMidYMid slice">
      <rect width="400" height="400" fill="#0e0e12" />
      {/* river dal */}
      <path d="M -10 220 Q 80 200 140 240 Q 200 280 280 250 Q 360 230 420 260" stroke="#1a3a4a" strokeWidth="22" fill="none" opacity="0.5"/>
      <path d="M -10 220 Q 80 200 140 240 Q 200 280 280 250 Q 360 230 420 260" stroke="#234855" strokeWidth="2" fill="none" opacity="0.9"/>
      {/* mountains */}
      <path d="M 0 60 L 60 30 L 110 70 L 170 25 L 230 75 L 290 35 L 360 70 L 400 50 L 400 100 L 0 100 Z" fill="#15151a" />
      <path d="M 0 80 L 80 55 L 140 95 L 200 60 L 270 100 L 340 70 L 400 90 L 400 130 L 0 130 Z" fill="#1a1a20" />
      {/* roads */}
      <line x1="0" y1="150" x2="400" y2="170" stroke="#2a2a32" strokeWidth="3"/>
      <line x1="200" y1="0" x2="220" y2="400" stroke="#2a2a32" strokeWidth="3"/>
      <line x1="0" y1="320" x2="400" y2="300" stroke="#2a2a32" strokeWidth="2"/>
      <line x1="80" y1="0" x2="100" y2="400" stroke="#2a2a32" strokeWidth="2"/>
      <line x1="320" y1="0" x2="340" y2="400" stroke="#2a2a32" strokeWidth="2"/>
      {/* labels */}
      <text x="20" y="40" fill="#3a3a42" fontSize="9" fontFamily="monospace">PIR PANJAL</text>
      <text x="290" y="195" fill="#3a3a42" fontSize="9" fontFamily="monospace">DAL LAKE</text>
      <text x="100" y="360" fill="#3a3a42" fontSize="9" fontFamily="monospace">CHADORA</text>
    </svg>
  );
}

// ============ CONTACT ============
const SERVICE_OPTIONS = SERVICES.filter(s => !s.soon).map(s => s.name);

function Contact({ accent }) {
  const [form, setForm] = useState({
    name: "", phone: "", vehicle: "", service: SERVICE_OPTIONS[0], date: "", message: ""
  });
  const [errors, setErrors] = useState({});
  const [sent, setSent] = useState(false);
  const [touched, setTouched] = useState({});

  const validate = (f) => {
    const e = {};
    if (!f.name.trim()) e.name = "Tell us your name";
    if (!f.phone.trim()) e.phone = "We need a number to confirm";
    else if (!/^[0-9+\s-]{7,}$/.test(f.phone)) e.phone = "That doesn't look like a phone number";
    if (!f.vehicle.trim()) e.vehicle = "Which car?";
    if (!f.date) e.date = "Pick a date";
    return e;
  };

  const onChange = (k) => (e) => {
    const next = { ...form, [k]: e.target.value };
    setForm(next);
    if (touched[k]) setErrors(validate(next));
  };
  const onBlur = (k) => () => {
    setTouched({ ...touched, [k]: true });
    setErrors(validate(form));
  };

  const onSubmit = (e) => {
    e.preventDefault();
    const eMap = validate(form);
    setErrors(eMap);
    setTouched({ name: true, phone: true, vehicle: true, date: true });
    if (Object.keys(eMap).length === 0) {
      saveSubmission({
        name: form.name, phone: form.phone, vehicle: form.vehicle,
        service: form.service, date: form.date, message: form.message,
      });
      setSent(true);
    }
  };

  if (sent) {
    return (
      <section id="contact" className="section contact">
        <div className="contact__sent">
          <div className="contact__sent-icon" style={{ borderColor: accent, color: accent }}>✓</div>
          <h2 className="h2">Got it, {form.name.split(" ")[0]}.</h2>
          <p className="lead">
            We'll call you on <b>{form.phone}</b> to confirm your <b>{form.service.toLowerCase()}</b> on <b>{form.date}</b>.
          </p>
          <p className="muted">Shukriya for choosing DrivZy.</p>
          <button className="btn btn--ghost" onClick={() => { setSent(false); setForm({ name: "", phone: "", vehicle: "", service: SERVICE_OPTIONS[0], date: "", message: "" }); setTouched({}); setErrors({}); }}>
            Book another
          </button>
        </div>
      </section>
    );
  }

  const today = new Date().toISOString().split("T")[0];

  return (
    <section id="contact" className="section contact">
      <div className="contact__left">
        <span className="eyebrow">Book a slot</span>
        <h2 className="h2">Tell us what your ride needs.</h2>
        <p className="lead">We'll call you back within an hour to confirm time and pricing.</p>
        <div className="contact__direct">
          <a href="tel:+917006925008" className="contact__direct-row">
            <span className="contact__direct-icon" style={{ background: accent + "20", color: accent }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M20 17l-3-1c-.7-.2-1.5 0-2 .5l-1 1c-2-1-4-3-5-5l1-1c.5-.5.7-1.3.5-2l-1-3c-.3-.8-1-1.3-2-1.3H5c-1 0-2 1-2 2 0 9 7 16 16 16 1 0 2-1 2-2v-2c0-.8-.5-1.5-1-1.7z"/></svg>
            </span>
            <div><b>Call</b><span>+91 70069 25008</span></div>
          </a>
          <a href="https://wa.me/917006925008" target="_blank" rel="noreferrer" className="contact__direct-row">
            <span className="contact__direct-icon" style={{ background: "#25d36620", color: "#25d366" }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M20 4 C 18 2 15 1 12 1 C 6 1 1 6 1 12 C 1 14 1.5 16 2.5 17.5 L 1 23 L 6.5 21.5 C 8 22.5 10 23 12 23 C 18 23 23 18 23 12 C 23 9 22 6 20 4 Z"/></svg>
            </span>
            <div><b>WhatsApp</b><span>+91 70069 25008</span></div>
          </a>
          <a href="#" className="contact__direct-row">
            <span className="contact__direct-icon" style={{ background: accent + "20", color: accent }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="0.8" fill="currentColor"/></svg>
            </span>
            <div><b>Instagram</b><span>@drivover.kashmir</span></div>
          </a>
          <a href="#" className="contact__direct-row">
            <span className="contact__direct-icon" style={{ background: accent + "20", color: accent }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/></svg>
            </span>
            <div><b>Email</b><span>hello@drivover.in</span></div>
          </a>
        </div>
      </div>
      <form className="contact__form" onSubmit={onSubmit} noValidate>
        <Field label="Your name" error={errors.name} touched={touched.name}>
          <input type="text" value={form.name} onChange={onChange("name")} onBlur={onBlur("name")} placeholder="e.g. Bilal Ahmad" />
        </Field>
        <Field label="Phone number" error={errors.phone} touched={touched.phone}>
          <input type="tel" value={form.phone} onChange={onChange("phone")} onBlur={onBlur("phone")} placeholder="+91 7000 000 000" />
        </Field>
        <Field label="Vehicle (make / model)" error={errors.vehicle} touched={touched.vehicle}>
          <input type="text" value={form.vehicle} onChange={onChange("vehicle")} onBlur={onBlur("vehicle")} placeholder="e.g. Hyundai Creta, Royal Enfield 350" />
        </Field>
        <Field label="Service required">
          <select value={form.service} onChange={onChange("service")}>
            {SERVICE_OPTIONS.map((o) => <option key={o}>{o}</option>)}
          </select>
        </Field>
        <Field label="Preferred date" error={errors.date} touched={touched.date}>
          <input type="date" value={form.date} onChange={onChange("date")} onBlur={onBlur("date")} min={today} />
        </Field>
        <Field label="Anything else? (optional)" full>
          <textarea rows="3" value={form.message} onChange={onChange("message")} placeholder="Pickup needed? Specific stains? Tell us." />
        </Field>
        <button type="submit" className="btn btn--accent btn--lg">
          Confirm booking
          <svg width="16" height="16" viewBox="0 0 16 16"><path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </button>
        <p className="contact__legal">By booking, you agree to receive a confirmation call from our team.</p>
      </form>
    </section>
  );
}

function Field({ label, error, touched, full, children }) {
  return (
    <label className={"field" + (full ? " field--full" : "") + (error && touched ? " field--err" : "")}>
      <span className="field__label">{label}</span>
      {children}
      {error && touched && <span className="field__err">{error}</span>}
    </label>
  );
}

// ============ FOOTER ============
function Footer({ accent }) {
  return (
    <footer className="footer">
      <div className="footer__top">
        <div className="footer__brand">
          <Wordmark accent={accent} />
          <p>Complete care under one roof, in Chadoora, Budgam &mdash; cars, SUVs, bikes, and anything else with wheels.</p>
        </div>
        <div className="footer__cols">
          <div>
            <h6>Visit</h6>
            <span>Check Chadura, Batpur</span>
            <span>Kralpora Road, Chadoora</span>
            <span>Budgam 191113</span>
            <span>+91 70069 25008</span>
          </div>
          <div>
            <h6>Hours</h6>
            <span>Mon — Sat · 9 to 8</span>
            <span>Sun · 10 to 4</span>
            <span>Fri · closed 1—2pm</span>
          </div>
          <div>
            <h6>Links</h6>
            {NAV_LINKS.map((l) => (
              <a key={l.id} href={"#" + l.id} onClick={(e) => { e.preventDefault(); document.getElementById(l.id).scrollIntoView({ behavior: "smooth" }); }}>{l.label}</a>
            ))}
          </div>
          <div>
            <h6>Follow</h6>
            <a href="https://www.instagram.com" target="_blank" rel="noreferrer">Instagram</a>
            <a href="https://wa.me/917006925008" target="_blank" rel="noreferrer">WhatsApp</a>
            <a href="mailto:hello@drivover.in">Email</a>
            <a href="admin.html" className="footer__admin">Studio admin →</a>
          </div>
        </div>
      </div>
      <div className="footer__bottom">
        <span>© {new Date().getFullYear()} DrivOver Detailing Studio · Chadoora, Budgam</span>
        <span>Made with care in Kashmir.</span>
      </div>
    </footer>
  );
}

// ============ TESTIMONIALS / REVIEWS ============
function Testimonials({ accent }) {
  const [items, setItems] = useState(loadReviews);
  const [showAll, setShowAll] = useState(false);
  const [showForm, setShowForm] = useState(false);
  useEffect(() => {
    const onUpdate = () => setItems(loadReviews());
    window.addEventListener("drivover:reviews", onUpdate);
    return () => window.removeEventListener("drivover:reviews", onUpdate);
  }, []);
  const visible = items.slice(0, 10);
  const avg = items.length ? (items.reduce((a, r) => a + r.rating, 0) / items.length).toFixed(1) : "5.0";
  return (
    <section id="reviews" className="section testimonials">
      <div className="reviews__head">
        <div>
          <span className="eyebrow">What people say</span>
          <h2 className="h2">Trusted by Kashmiri riders &amp; drivers.</h2>
          <p className="lead">
            <span style={{ color: accent }}>★ {avg}</span> from <b>{items.length}</b> review{items.length === 1 ? "" : "s"} · every word is from a real customer.
          </p>
        </div>
        <button className="btn btn--accent" onClick={() => setShowForm(true)}>
          Leave a review
          <svg width="14" height="14" viewBox="0 0 16 16"><path d="M8 2 L10 6 L14 6.5 L11 9.5 L12 14 L8 11.5 L4 14 L5 9.5 L2 6.5 L6 6 Z" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinejoin="round"/></svg>
        </button>
      </div>
      <div className="testimonials__grid">
        {visible.map((t) => (
          <div key={t.id} className="testimonial">
            <div className="testimonial__stars" style={{ color: accent }}>{"\u2605".repeat(t.rating)}<span style={{ color: "rgba(255,255,255,0.12)" }}>{"\u2605".repeat(5 - t.rating)}</span></div>
            <p>"{t.text}"</p>
            <div className="testimonial__meta">
              <span className="testimonial__avatar" style={{ background: accent + "33", color: accent }}>{(t.name || "?")[0].toUpperCase()}</span>
              <div><b>{t.name}</b><span>{t.area}</span></div>
            </div>
          </div>
        ))}
      </div>
      {items.length > 10 && (
        <div className="reviews__more">
          <button className="btn btn--ghost" onClick={() => setShowAll(true)}>
            See all {items.length} reviews →
          </button>
        </div>
      )}
      {showAll && <ReviewsModal items={items} accent={accent} onClose={() => setShowAll(false)} />}
      {showForm && <ReviewForm accent={accent} onClose={() => setShowForm(false)} />}
    </section>
  );
}

function ReviewsModal({ items, accent, onClose }) {
  useEffect(() => {
    document.body.style.overflow = "hidden";
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => { document.body.style.overflow = ""; window.removeEventListener("keydown", onKey); };
  }, []);
  return (
    <div className="rmodal" onClick={onClose}>
      <div className="rmodal__panel" onClick={(e) => e.stopPropagation()}>
        <div className="rmodal__head">
          <div>
            <span className="eyebrow">All reviews · {items.length}</span>
            <h3 className="rmodal__title">Every voice, in their words.</h3>
          </div>
          <button className="rmodal__close" onClick={onClose} aria-label="Close">×</button>
        </div>
        <div className="rmodal__list">
          {items.map((t) => (
            <div key={t.id} className="rmodal__item">
              <div className="rmodal__item-head">
                <span className="testimonial__avatar" style={{ background: accent + "33", color: accent }}>{(t.name || "?")[0].toUpperCase()}</span>
                <div className="rmodal__item-who">
                  <b>{t.name}</b>
                  <span>{t.area}</span>
                </div>
                <span className="rmodal__item-stars" style={{ color: accent }}>{"\u2605".repeat(t.rating)}</span>
              </div>
              <p>"{t.text}"</p>
              <span className="rmodal__item-date">{new Date(t.ts).toLocaleDateString("en-IN", { day: "numeric", month: "short", year: "numeric" })}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function ReviewForm({ accent, onClose }) {
  const [name, setName] = useState("");
  const [area, setArea] = useState("");
  const [rating, setRating] = useState(5);
  const [text, setText] = useState("");
  const [hover, setHover] = useState(0);
  const [err, setErr] = useState({});
  const [done, setDone] = useState(false);
  useEffect(() => {
    document.body.style.overflow = "hidden";
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => { document.body.style.overflow = ""; window.removeEventListener("keydown", onKey); };
  }, []);
  const submit = (e) => {
    e.preventDefault();
    const x = {};
    if (!name.trim()) x.name = "Tell us your name";
    if (!text.trim() || text.trim().length < 8) x.text = "Write at least a sentence";
    setErr(x);
    if (Object.keys(x).length) return;
    saveReview({ name: name.trim(), area: area.trim() || "Kashmir", rating, text: text.trim() });
    setDone(true);
    setTimeout(onClose, 1600);
  };
  return (
    <div className="rmodal" onClick={onClose}>
      <div className="rmodal__panel rmodal__panel--form" onClick={(e) => e.stopPropagation()}>
        <div className="rmodal__head">
          <div>
            <span className="eyebrow">Share your experience</span>
            <h3 className="rmodal__title">How did we do?</h3>
          </div>
          <button className="rmodal__close" onClick={onClose} aria-label="Close">×</button>
        </div>
        {done ? (
          <div className="rform__done">
            <div className="contact__sent-icon" style={{ borderColor: accent, color: accent }}>✓</div>
            <h4>Shukriya, {name.split(" ")[0]}!</h4>
            <p>Your review is now live on the site.</p>
          </div>
        ) : (
          <form className="rform" onSubmit={submit} noValidate>
            <div className="rform__stars">
              <span className="field__label">Your rating</span>
              <div className="rform__star-row" onMouseLeave={() => setHover(0)}>
                {[1,2,3,4,5].map((n) => (
                  <button type="button" key={n}
                    className="rform__star"
                    onMouseEnter={() => setHover(n)}
                    onClick={() => setRating(n)}
                    style={{ color: (hover || rating) >= n ? accent : "rgba(255,255,255,0.15)" }}
                    aria-label={n + " stars"}>★</button>
                ))}
                <span className="rform__rating-num">{(hover || rating)}/5</span>
              </div>
            </div>
            <Field label="Your name" error={err.name} touched={!!err.name}>
              <input value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Bilal Ahmad" />
            </Field>
            <Field label="Area (optional)">
              <input value={area} onChange={(e) => setArea(e.target.value)} placeholder="e.g. Budgam" />
            </Field>
            <Field label="Your review" full error={err.text} touched={!!err.text}>
              <textarea rows="4" value={text} onChange={(e) => setText(e.target.value)} placeholder="How was the service? Any details we should know?" />
            </Field>
            <button type="submit" className="btn btn--accent btn--lg rform__submit">Post my review</button>
          </form>
        )}
      </div>
    </div>
  );
}

// ============ MISC ============
function SectionHead({ eyebrow, title, sub }) {
  return (
    <div className="section__head">
      <span className="eyebrow">{eyebrow}</span>
      <h2 className="h2">{title}</h2>
      {sub && <p className="lead">{sub}</p>}
    </div>
  );
}

function FloatingCTAs({ accent }) {
  return (
    <div className="floats">
      <a href="tel:+917006925008" className="float float--call" aria-label="Call now">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M20 17l-3-1c-.7-.2-1.5 0-2 .5l-1 1c-2-1-4-3-5-5l1-1c.5-.5.7-1.3.5-2l-1-3c-.3-.8-1-1.3-2-1.3H5c-1 0-2 1-2 2 0 9 7 16 16 16 1 0 2-1 2-2v-2c0-.8-.5-1.5-1-1.7z"/></svg>
      </a>
      <a href="https://wa.me/917006925008" target="_blank" rel="noreferrer" className="float float--wa" aria-label="WhatsApp">
        <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M20 4 C 18 2 15 1 12 1 C 6 1 1 6 1 12 C 1 14 1.5 16 2.5 17.5 L 1 23 L 6.5 21.5 C 8 22.5 10 23 12 23 C 18 23 23 18 23 12 C 23 9 22 6 20 4 Z"/></svg>
      </a>
    </div>
  );
}

// ============ APP ============
function App() {
  const [tweaks, setTweak] = (window.useTweaks || (() => [TWEAK_DEFAULTS, () => {}]))(TWEAK_DEFAULTS);
  const accentObj = ACCENTS[tweaks.accent] || ACCENTS.saffron;

  useEffect(() => {
    document.documentElement.style.setProperty("--accent", accentObj.hex);
    document.documentElement.style.setProperty("--accent-soft", accentObj.soft);
    document.documentElement.style.setProperty("--accent-glow", accentObj.glow);
  }, [tweaks.accent]);

  const goToBook = () => {
    const el = document.getElementById("contact");
    if (el) el.scrollIntoView({ behavior: "smooth" });
  };

  return (
    <div className="app" data-screen-label="DrivOver Site">
      <Nav accent={accentObj.hex} onBook={goToBook} />
      <Hero accent={accentObj.hex} variant={tweaks.heroVariant} onBook={goToBook} />
      <Services accent={accentObj.hex} onBook={goToBook} />
      <About accent={accentObj.hex} />
      <Gallery accent={accentObj.hex} />
      <Testimonials accent={accentObj.hex} />
      <Location accent={accentObj.hex} />
      <Contact accent={accentObj.hex} />
      <Footer accent={accentObj.hex} />
      {tweaks.showFloatingCTAs && <FloatingCTAs accent={accentObj.hex} />}

      {window.TweaksPanel && (
        <window.TweaksPanel>
          <window.TweakSection label="Brand">
            <window.TweakRadio
              label="Accent"
              value={tweaks.accent}
              options={["saffron", "steel", "ice"]}
              onChange={(v) => setTweak("accent", v)}
            />
          </window.TweakSection>
          <window.TweakSection label="Layout">
            <window.TweakToggle
              label="Floating call & WhatsApp"
              value={tweaks.showFloatingCTAs}
              onChange={(v) => setTweak("showFloatingCTAs", v)}
            />
          </window.TweakSection>
        </window.TweaksPanel>
      )}
    </div>
  );
}

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