// ARS — app shell: nav, admin mode, bookings, mount
const { useState: useStateApp, useEffect: useEffectApp } = React;

const NAV_LINKS = [["#services", "Services"], ["#how", "How it works"], ["#about", "About"], ["#availability", "Availability"], ["#faq", "FAQ"], ["#contact", "Contact"]];

function Nav({ onBook, adminOffset }) {
  const [scrolled, setScrolled] = useStateApp(false);
  const [menu, setMenu] = useStateApp(false);
  useEffectApp(() => {
    const f = () => setScrolled(window.scrollY > 40);
    f(); window.addEventListener("scroll", f); return () => window.removeEventListener("scroll", f);
  }, []);
  const solid = scrolled || menu;
  return (
    <header style={{ position: "fixed", top: adminOffset, left: 0, right: 0, zIndex: 100, transition: "all .25s",
      background: solid ? "rgba(255,255,255,.92)" : "transparent", backdropFilter: solid ? "blur(10px)" : "none",
      borderBottom: solid ? "1px solid var(--line)" : "1px solid transparent" }}>
      <div className="wrap" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", height: 70 }}>
        <a href="#home" style={{ display: "flex", alignItems: "center", gap: 11 }}>
          <img src={LOGO} alt="ARS" style={{ width: 44, height: 44 }} />
          <span style={{ fontWeight: 800, fontSize: 17, lineHeight: 1, color: solid ? "var(--navy)" : "#fff" }}>
            ARS<span style={{ color: solid ? "var(--green)" : "var(--ball)" }}> Mobile</span></span>
        </a>
        <nav style={{ display: "flex", alignItems: "center", gap: 26 }} className="ars-desktop-nav">
          {NAV_LINKS.map(([h, l]) => (
            <a key={h} href={h} style={{ fontWeight: 600, fontSize: 14.5, color: solid ? "var(--ink)" : "rgba(255,255,255,.88)" }}>{l}</a>
          ))}
          <button className="btn btn-green btn-sm" onClick={onBook} style={{ padding: "11px 20px", fontSize: 14 }}>Book now</button>
        </nav>
        <button className="ars-mobile-burger" onClick={() => setMenu(!menu)} style={{ display: "none", color: solid ? "var(--navy)" : "#fff" }}>
          <Icon name={menu ? "x" : "racquet"} size={26} />
        </button>
      </div>
      {menu && (
        <div className="wrap" style={{ paddingBottom: 18, display: "flex", flexDirection: "column", gap: 4 }}>
          {NAV_LINKS.map(([h, l]) => (
            <a key={h} href={h} onClick={() => setMenu(false)} style={{ fontWeight: 700, padding: "11px 0", borderBottom: "1px solid var(--line)", color: "var(--navy)" }}>{l}</a>
          ))}
          <button className="btn btn-green" onClick={() => { setMenu(false); onBook(); }} style={{ marginTop: 12 }}>Book now</button>
        </div>
      )}
      <style>{`
        @media (max-width:880px){
          .ars-desktop-nav{display:none !important;}
          .ars-mobile-burger{display:block !important;}
        }`}</style>
    </header>
  );
}

/* ---------- admin PIN modal ---------- */
function PinModal({ onClose, onOk }) {
  const [pin, setPin] = useStateApp("");
  const [err, setErr] = useStateApp(false);
  const go = () => { if (pin === window.ARS.ADMIN_PIN) onOk(); else { setErr(true); setPin(""); } };
  return (
    <div onClick={(e) => e.target === e.currentTarget && onClose()}
      style={{ position: "fixed", inset: 0, zIndex: 200, background: "rgba(14,38,73,.55)", backdropFilter: "blur(4px)", display: "grid", placeItems: "center", padding: 16 }}>
      <div className="rise card" style={{ width: "100%", maxWidth: 380, padding: 30, textAlign: "center", boxShadow: "var(--shadow-lg)" }}>
        <div style={{ width: 56, height: 56, borderRadius: 14, background: "var(--navy-soft)", color: "var(--navy)", display: "grid", placeItems: "center", margin: "0 auto 14px" }}><Icon name="lock" size={26} /></div>
        <h3 style={{ fontSize: 21, color: "var(--navy)" }}>Owner access</h3>
        <p style={{ color: "var(--ink-2)", fontSize: 14, marginTop: 6 }}>Enter your PIN to edit pricing & view bookings.</p>
        <input autoFocus type="password" inputMode="numeric" value={pin} placeholder="••••"
          onChange={(e) => { setPin(e.target.value); setErr(false); }} onKeyDown={(e) => e.key === "Enter" && go()}
          style={{ width: 160, textAlign: "center", letterSpacing: ".4em", fontSize: 24, fontWeight: 800, padding: "12px",
            borderRadius: 12, border: `2px solid ${err ? "#c0413a" : "var(--line)"}`, margin: "16px auto 0", display: "block", outline: "none" }} />
        {err && <div style={{ color: "#c0413a", fontWeight: 700, fontSize: 13, marginTop: 8 }}>Incorrect PIN — try again</div>}
        <div style={{ fontSize: 12, color: "var(--ink-2)", marginTop: 10 }}>Demo PIN: <b>1990</b></div>
        <div style={{ display: "flex", gap: 10, marginTop: 18 }}>
          <button className="btn btn-ghost" style={{ flex: 1, justifyContent: "center" }} onClick={onClose}>Cancel</button>
          <button className="btn btn-navy" style={{ flex: 1, justifyContent: "center" }} onClick={go}>Unlock</button>
        </div>
      </div>
    </div>
  );
}

/* ---------- bookings drawer ---------- */
function BookingsDrawer({ bookings, setBookings, onClose }) {
  const remove = (id) => setBookings(bookings.filter((b) => b.id !== id));
  const cycle = (id) => {
    const order = ["New", "Confirmed", "Done"];
    setBookings(bookings.map((b) => b.id === id ? { ...b, status: order[(order.indexOf(b.status) + 1) % 3] } : b));
  };
  const statusColor = { New: "var(--ball-deep)", Confirmed: "var(--green)", Done: "var(--navy)" };
  return (
    <div onClick={(e) => e.target === e.currentTarget && onClose()} style={{ position: "fixed", inset: 0, zIndex: 190, background: "rgba(14,38,73,.5)", backdropFilter: "blur(3px)" }}>
      <div className="rise" style={{ position: "absolute", top: 0, right: 0, bottom: 0, width: "min(460px,100%)", background: "var(--paper)", boxShadow: "var(--shadow-lg)", display: "flex", flexDirection: "column" }}>
        <div style={{ padding: "20px 22px", background: "var(--navy-deep)", color: "#fff", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div><div style={{ fontWeight: 800, fontSize: 18 }}>Bookings</div><div style={{ fontSize: 13, color: "rgba(255,255,255,.6)" }}>{bookings.length} total</div></div>
          <button onClick={onClose} style={{ color: "#fff" }}><Icon name="x" size={24} /></button>
        </div>
        <div style={{ flex: 1, overflowY: "auto", padding: 18, display: "grid", gap: 12, alignContent: "start" }}>
          {bookings.length === 0 && <div style={{ textAlign: "center", color: "var(--ink-2)", marginTop: 60 }}>
            <BallMark size={52} style={{ margin: "0 auto 14px" }} /><p>No bookings yet.<br />New online bookings show up here.</p></div>}
          {bookings.slice().reverse().map((b) => (
            <div key={b.id} className="card" style={{ padding: 16, boxShadow: "var(--shadow)" }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 10 }}>
                <div>
                  <div style={{ fontWeight: 800, color: "var(--navy)", fontSize: 16 }}>{b.name}</div>
                  <div style={{ fontSize: 13, color: "var(--ink-2)" }}>{b.day} · {b.slot}</div>
                </div>
                <button onClick={() => cycle(b.id)} style={{ fontWeight: 800, fontSize: 11, letterSpacing: ".06em", textTransform: "uppercase",
                  padding: "5px 11px", borderRadius: 100, color: "#fff", background: statusColor[b.status] }}>{b.status}</button>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "4px 14px", marginTop: 12, fontSize: 13.5 }}>
                <div><b>Service:</b> {b.service}</div>
                <div><b>Racquets:</b> {b.count}</div>
                <div style={{ gridColumn: "1 / -1" }}><b>String:</b> {b.string}</div>
                <div style={{ gridColumn: "1 / -1" }}><b>Phone:</b> <a href={`tel:${b.phone}`} style={{ color: "var(--green-deep)", fontWeight: 700 }}>{b.phone}</a>{b.email ? ` · ${b.email}` : ""}</div>
                {b.address && <div style={{ gridColumn: "1 / -1" }}><b>Location:</b> {b.address}</div>}
                {b.notes && <div style={{ gridColumn: "1 / -1", color: "var(--ink-2)" }}><b style={{ color: "var(--ink)" }}>Notes:</b> {b.notes}</div>}
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--line)" }}>
                <span style={{ fontWeight: 800, color: "var(--navy)" }}>Est. ${b.total}{b.stencil ? " · stencil" : ""}{b.pickup ? " · pickup" : ""}</span>
                <button onClick={() => remove(b.id)} style={{ color: "#c0413a", display: "flex", gap: 5, alignItems: "center", fontWeight: 700, fontSize: 13 }}><Icon name="trash" size={16} /> Delete</button>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ---------- admin toolbar ---------- */
function AdminBar({ bookingCount, onBookings, onReset, onExit }) {
  return (
    <div style={{ position: "fixed", top: 0, left: 0, right: 0, zIndex: 120, height: 46, background: "var(--ink)", color: "#fff",
      display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 18px", fontSize: 13.5 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 9, fontWeight: 700 }}>
        <span style={{ width: 9, height: 9, borderRadius: "50%", background: "var(--ball)", boxShadow: "0 0 0 4px rgba(216,230,59,.2)" }} />
        Owner mode — prices are editable
      </div>
      <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
        <button onClick={onBookings} className="btn btn-sm" style={{ background: "rgba(255,255,255,.12)", color: "#fff" }}>
          <Icon name="calendar" size={15} /> Bookings <span style={{ background: "var(--ball)", color: "var(--navy-deep)", borderRadius: 100, padding: "1px 8px", fontWeight: 800, marginLeft: 2 }}>{bookingCount}</span></button>
        <button onClick={onReset} className="btn btn-sm" style={{ background: "rgba(255,255,255,.12)", color: "#fff" }}>Reset prices</button>
        <button onClick={onExit} className="btn btn-sm" style={{ background: "var(--ball)", color: "var(--navy-deep)" }}>Exit</button>
      </div>
    </div>
  );
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "ballMotion": "float",
  "ballSpeed": 4,
  "ringPulse": true
}/*EDITMODE-END*/;

function App() {
  const [data, setData] = useStateApp(() => window.ARS.loadPricing());
  const [bookings, setBookings] = useStateApp(() => window.ARS.loadBookings());
  const [booking, setBooking] = useStateApp(false);
  const [admin, setAdmin] = useStateApp(false);
  const [showPin, setShowPin] = useStateApp(false);
  const [showBookings, setShowBookings] = useStateApp(false);
  const [toast, showToast] = useToast();
  const [tw, setTweak] = useTweaks(TWEAK_DEFAULTS);

  useEffectApp(() => {
    const root = document.documentElement;
    root.dataset.ballMotion = tw.ballMotion;
    root.dataset.ringPulse = tw.ringPulse ? "on" : "off";
    // speed 1 (slow) → 16s, speed 10 (fast) → 2s
    const dur = (16 - (tw.ballSpeed - 1) * (14 / 9)).toFixed(2);
    root.style.setProperty("--ball-dur", dur + "s");
  }, [tw.ballMotion, tw.ballSpeed, tw.ringPulse]);

  useEffectApp(() => { window.ARS.savePricing(data); }, [data]);
  useEffectApp(() => { window.ARS.saveBookings(bookings); }, [bookings]);
  useEffectApp(() => {
    const handleBookHash = () => {
      if (window.location.hash === "#book") {
        setBooking(true);
        history.replaceState(null, "", window.location.pathname + window.location.search);
      }
    };
    handleBookHash();
    window.addEventListener("hashchange", handleBookHash);
    return () => window.removeEventListener("hashchange", handleBookHash);
  }, []);

  const completeBooking = (bk) => { setBookings((p) => [...p, bk]); };
  const resetPrices = () => { if (confirm("Reset all pricing back to defaults?")) { setData(window.ARS.resetPricing()); showToast("Pricing reset to defaults"); } };

  const openBook = () => setBooking(true);

  return (
    <div style={{ paddingTop: admin ? 46 : 0, transition: "padding .2s" }}>
      {admin && <AdminBar bookingCount={bookings.length} onBookings={() => setShowBookings(true)} onReset={resetPrices} onExit={() => setAdmin(false)} />}
      <Nav onBook={openBook} adminOffset={admin ? 46 : 0} />
      <main>
        <Hero onBook={openBook} />
        <HowItWorks />
        <Stats />
        <Services data={data} setData={(d) => setData(d)} editing={admin} onBook={openBook} />
        <About />
        <ServiceArea />
        <FAQ />
        <Contact onBook={openBook} />
      </main>
      <Footer />

      {/* owner access trigger */}
      {!admin && (
        <button onClick={() => setShowPin(true)} title="Owner login"
          style={{ position: "fixed", bottom: 20, right: 20, zIndex: 90, width: 46, height: 46, borderRadius: "50%",
            background: "var(--navy)", color: "#fff", display: "grid", placeItems: "center", boxShadow: "var(--shadow-lg)", opacity: .55 }}
          onMouseEnter={(e) => e.currentTarget.style.opacity = 1} onMouseLeave={(e) => e.currentTarget.style.opacity = .55}>
          <Icon name="lock" size={20} />
        </button>
      )}

      {booking && <BookingModal data={data} onClose={() => setBooking(false)} onComplete={completeBooking} />}
      {showPin && <PinModal onClose={() => setShowPin(false)} onOk={() => { setShowPin(false); setAdmin(true); showToast("Owner mode on — edit any price"); }} />}
      {showBookings && <BookingsDrawer bookings={bookings} setBookings={setBookings} onClose={() => setShowBookings(false)} />}
      {toast}

      <TweaksPanel>
        <TweakSection label="Hero tennis ball" />
        <TweakSelect label="Motion" value={tw.ballMotion}
          options={[{ value: "float", label: "Float" }, { value: "spin", label: "Spin" }, { value: "bounce", label: "Bounce" }, { value: "pulse", label: "Pulse" }, { value: "off", label: "Off" }]}
          onChange={(v) => setTweak("ballMotion", v)} />
        <TweakSlider label="Speed" value={tw.ballSpeed} min={1} max={10} step={1}
          onChange={(v) => setTweak("ballSpeed", v)} />
        <TweakToggle label="Pulse the dashed ring" value={tw.ringPulse}
          onChange={(v) => setTweak("ringPulse", v)} />
      </TweaksPanel>
    </div>
  );
}

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