/* Oakmere Club — mockup. React via CDN + Babel, no build step.
   Edit + refresh (auto-reloads). Fake data in data/data.js.
   Single file on purpose: in-browser Babel makes multi-file scope fragile and
   un-testable headlessly here, so we keep one reliable file until it hurts. */

const { useState, useMemo } = React;

/* ============================ icons ============================ */
function Icon({ name, className = "w-6 h-6" }) {
  const p = {
    tennis: <><circle cx="12" cy="12" r="9" /><path d="M5 5a13 13 0 0 1 0 14M19 5a13 13 0 0 0 0 14" /></>,
    golf: <><path d="M12 3v13" /><path d="M12 3l7 3-7 3" /><path d="M7 21h10" /><path d="M9 17c0 1.5 1.3 2 3 2" /></>,
    dining: <><path d="M5 3v8a2 2 0 0 0 4 0V3M7 11v10M17 3c-1.5 0-2.5 1.8-2.5 4.5S15.5 12 17 12v9" /></>,
    cafe: <><path d="M4 8h13v5a5 5 0 0 1-5 5H9a5 5 0 0 1-5-5V8Z" /><path d="M17 9h2a2 2 0 0 1 0 4h-2" /><path d="M7 3v2M11 3v2" /></>,
    bell: <><path d="M6 9a6 6 0 1 1 12 0c0 5 2 6 2 6H4s2-1 2-6Z" /><path d="M10 19a2 2 0 0 0 4 0" /></>,
    search: <><circle cx="11" cy="11" r="7" /><path d="m20 20-3-3" /></>,
    chevron: <path d="m9 6 6 6-6 6" />,
    back: <path d="m15 6-6 6 6 6" />,
    home: <><path d="m4 11 8-7 8 7" /><path d="M6 10v9h12v-9" /></>,
    calendar: <><rect x="4" y="5" width="16" height="16" rx="2" /><path d="M4 9h16M9 3v4M15 3v4" /></>,
    activity: <path d="M4 12h4l2 6 4-12 2 6h4" />,
    user: <><circle cx="12" cy="8" r="4" /><path d="M4 20a8 8 0 0 1 16 0" /></>,
    clock: <><circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 2" /></>,
    pin: <><path d="M12 21s7-6.3 7-12a7 7 0 1 0-14 0c0 5.7 7 12 7 12Z" /><circle cx="12" cy="9" r="2.5" /></>,
    users: <><circle cx="9" cy="8" r="3.5" /><path d="M3 20a6 6 0 0 1 12 0" /><path d="M16 5a3.5 3.5 0 0 1 0 7M21 20a6 6 0 0 0-5-5.9" /></>,
    plus: <><path d="M12 5v14M5 12h14" /></>,
    check: <path d="m5 13 4 4L19 7" />,
    close: <path d="M6 6l12 12M18 6 6 18" />,
    cart: <><circle cx="7" cy="19" r="1.6" /><circle cx="16" cy="19" r="1.6" /><path d="M3 4h2l2 11h10l2-7H6" /></>,
    walk: <><circle cx="13" cy="4" r="1.6" /><path d="M13 7l-2 4 3 2 1 5M11 11l-3 2-1 4M14 9l3 1" /></>,
    flag: <><path d="M6 21V4M6 4l11 3-3 3 3 3-11 2" /></>,
  }[name];
  return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"
              strokeLinecap="round" strokeLinejoin="round" className={className}>{p}</svg>;
}

/* ============================ shared bits ============================ */
function Chip({ children, tone = "neutral" }) {
  const tones = {
    open: "bg-emerald-50 text-emerald-700", closed: "bg-stone-100 text-stone-500",
    neutral: "bg-stone-100 text-stone-600", gold: "bg-amber-50 text-amber-700",
    club: "bg-club-50 text-club-700",
  };
  return <span className={`inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full ${tones[tone]}`}>{children}</span>;
}

function Avatar({ person, className = "w-9 h-9 text-xs" }) {
  return <div className={`rounded-full bg-club-50 text-club-700 grid place-items-center font-semibold ring-2 ring-white ${className}`}>{person.initials}</div>;
}

function Segmented({ options, value, onChange }) {
  return (
    <div className="inline-flex bg-stone-100 rounded-xl p-1 gap-1">
      {options.map((o) => (
        <button key={o.value} onClick={() => onChange(o.value)}
          className={`px-3.5 py-1.5 rounded-lg text-sm font-medium transition ${value === o.value ? "bg-white text-club-700 shadow-sm" : "text-stone-500"}`}>
          {o.label}
        </button>
      ))}
    </div>
  );
}

/* ============================ navigation ============================ */
/* tiny built-in router — no library for a 4-screen mockup */
function BottomNav({ navigate, active }) {
  const items = [["home", "Home"], ["calendar", "Bookings"], ["activity", "Activity"], ["user", "Profile"]];
  return (
    <nav className="fixed bottom-0 left-1/2 -translate-x-1/2 w-full max-w-[440px] bg-white/90 backdrop-blur border-t border-stone-100 px-6 py-2.5 flex justify-between z-30">
      {items.map(([icon, label]) => (
        <button key={label} onClick={() => label === "Home" && navigate("home")}
          className={`flex flex-col items-center gap-1 text-[11px] font-medium ${active === label ? "text-club-700" : "text-stone-400"}`}>
          <Icon name={icon} className="w-6 h-6" />{label}
        </button>
      ))}
    </nav>
  );
}

/* ============================ HOME ============================ */
function TopBar({ club }) {
  return (
    <header className="flex items-center justify-between px-5 pt-6 pb-3">
      <div className="flex items-center gap-3">
        <div className="w-10 h-10 rounded-xl bg-club-700 text-white grid place-items-center font-serif text-lg shadow-sm">O</div>
        <div>
          <div className="text-[15px] font-semibold text-stone-800 leading-tight">{club.name}</div>
          <div className="text-xs text-stone-400 leading-tight">{club.tagline}</div>
        </div>
      </div>
      <button className="relative w-10 h-10 rounded-full grid place-items-center text-stone-500 hover:bg-stone-100 transition">
        <Icon name="bell" /><span className="absolute top-1.5 right-1.5 w-2.5 h-2.5 bg-rose-500 rounded-full ring-2 ring-white" />
      </button>
    </header>
  );
}

function UpcomingCard({ item }) {
  return (
    <div className="min-w-[230px] bg-white rounded-2xl border border-stone-100 shadow-sm p-4 flex gap-3">
      <div className="w-11 h-11 rounded-xl bg-club-50 text-club-700 grid place-items-center shrink-0"><Icon name={item.icon} /></div>
      <div className="min-w-0">
        <div className="text-sm font-semibold text-stone-800 truncate">{item.title}</div>
        <div className="text-xs text-stone-500 mt-0.5 flex items-center gap-1"><Icon name="clock" className="w-3.5 h-3.5" />{item.when}</div>
        <div className="text-xs text-stone-400 mt-1">{item.meta}</div>
      </div>
    </div>
  );
}

function AmenityCard({ a, onClick }) {
  const [c1, c2] = a.gradient;
  return (
    <button onClick={onClick} className="text-left rounded-3xl overflow-hidden shadow-sm border border-stone-100 bg-white active:scale-[0.99] transition">
      <div className="h-28 relative grid place-items-center" style={{ background: `linear-gradient(135deg, ${c1}, ${c2})` }}>
        <Icon name={a.icon} className="w-12 h-12 text-white/90" />
        <div className="absolute top-3 left-3"><Chip tone={a.open ? "open" : "closed"}>{a.open ? "Open now" : "Closed"}</Chip></div>
      </div>
      <div className="p-3.5">
        <div className="flex items-center justify-between">
          <div className="font-semibold text-stone-800">{a.name}</div><Icon name="chevron" className="w-4 h-4 text-stone-300" />
        </div>
        <div className="text-[11px] uppercase tracking-wide text-club-600 font-medium mt-0.5">{a.kind}</div>
        <div className="text-xs text-stone-500 mt-1.5 leading-snug">{a.blurb}</div>
        <div className="mt-2.5">{a.open ? <Chip tone="gold">{a.slotsToday} openings today</Chip> : <Chip tone="closed">Opens tomorrow 8:00a</Chip>}</div>
      </div>
    </button>
  );
}

function EventCard({ e }) {
  return (
    <div className="mx-5 rounded-3xl p-5 text-white shadow-sm" style={{ background: "linear-gradient(135deg,#14543e,#1c6b49)" }}>
      <Chip tone="gold">{e.spots}</Chip>
      <div className="text-lg font-semibold mt-3">{e.title}</div>
      <div className="text-sm text-white/80 mt-1 flex items-center gap-3">
        <span className="flex items-center gap-1"><Icon name="clock" className="w-4 h-4" />{e.when}</span>
        <span className="flex items-center gap-1"><Icon name="pin" className="w-4 h-4" />{e.where}</span>
      </div>
      <button className="mt-4 bg-white text-club-700 text-sm font-semibold rounded-xl px-4 py-2.5">Join the mixer</button>
    </div>
  );
}

function SectionTitle({ children, action, onAction }) {
  return (
    <div className="flex items-end justify-between px-5 mb-3">
      <h2 className="text-[17px] font-semibold text-stone-800">{children}</h2>
      {action && <button onClick={onAction} className="text-sm font-medium text-club-600">{action}</button>}
    </div>
  );
}

function HomeScreen({ navigate }) {
  const c = window.CLUB;
  const openAmenity = (a) => a.id === "golf" ? navigate("golf") : alert(`(${a.name}) flow — coming next!`);
  return (
    <div className="pb-24">
      <TopBar club={c} />
      <div className="px-5 pt-1 pb-4">
        <h1 className="text-2xl font-semibold text-stone-900 tracking-tight">Good morning, {c.member.first}</h1>
        <p className="text-sm text-stone-400 mt-0.5">{c.today}</p>
      </div>
      <div className="px-5 pb-5">
        <div className="flex items-center gap-3 bg-stone-100 rounded-2xl px-4 py-3 text-stone-400">
          <Icon name="search" className="w-5 h-5" /><span className="text-sm">Search courts, tee times, tables…</span>
        </div>
      </div>

      <SectionTitle action="See all">Your reservations</SectionTitle>
      <div className="flex gap-3 overflow-x-auto px-5 pb-1 mb-6 no-scrollbar">
        {c.upcoming.map((u) => <UpcomingCard key={u.id} item={u} />)}
      </div>

      <SectionTitle action="Map">Book an amenity</SectionTitle>
      <div className="grid grid-cols-2 gap-3.5 px-5 mb-7">
        {c.amenities.map((a) => <AmenityCard key={a.id} a={a} onClick={() => openAmenity(a)} />)}
      </div>

      <SectionTitle>Happening at the club</SectionTitle>
      {c.events.map((e) => <EventCard key={e.id} e={e} />)}
    </div>
  );
}

/* ============================ GOLF ============================ */
/* deterministic pseudo-random so availability is stable across reloads */
function seed(str) { let h = 2166136261; for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0; }
function rint(str, n) { return seed(str) % n; }

function fmtTime(h, m) {
  const ap = h >= 12 ? "PM" : "AM"; const hh = ((h + 11) % 12) + 1;
  return { h: hh, m: m.toString().padStart(2, "0"), ap };
}
function dayStrip() {
  const base = new Date("2026-06-05T00:00:00"); const wk = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
  return Array.from({ length: 10 }, (_, i) => { const d = new Date(base); d.setDate(base.getDate() + i);
    return { idx: i, wd: wk[d.getDay()], day: d.getDate(), key: `d${i}` }; });
}
function genTeeTimes(courseId, dateKey) {
  const G = window.CLUB.golf.golfers; const times = [];
  for (let h = 7; h <= 9; h++) for (let m = 0; m < 60; m += 10) times.push([h, m, "morning"]);
  for (let h = 11; h <= 12; h++) for (let m = 0; m < 60; m += 20) times.push([h, m, "midday"]);
  for (let h = 14; h <= 16; h++) for (let m = 0; m < 60; m += 20) times.push([h, m, "afternoon"]);
  return times.map(([h, m, period]) => {
    const key = `${courseId}|${dateKey}|${h}:${m}`;
    const fill = rint(key, 5);                       // 0..4 already in the group
    const off = rint(key + "p", G.length);
    const players = Array.from({ length: fill }, (_, k) => G[(off + k) % G.length]);
    return { id: key, h, m, period, players, open: 4 - fill, ...fmtTime(h, m) };
  });
}

function TeeTimeCard({ t, onSelect }) {
  const full = t.open === 0;
  return (
    <button disabled={full} onClick={() => onSelect(t)}
      className={`w-full text-left bg-white rounded-2xl border border-stone-100 shadow-sm p-4 flex items-center gap-4 transition ${full ? "opacity-50" : "active:scale-[0.99]"}`}>
      <div className="text-center w-14 shrink-0">
        <div className="text-xl font-semibold text-stone-800 leading-none">{t.h}:{t.m}</div>
        <div className="text-[11px] text-stone-400 mt-1">{t.ap}</div>
      </div>
      <div className="w-px self-stretch bg-stone-100" />
      <div className="flex-1 min-w-0">
        {t.players.length === 0 ? (
          <div className="text-sm font-medium text-club-700">Open tee time</div>
        ) : (
          <div className="flex -space-x-2 mb-1">{t.players.map((p, i) => <Avatar key={i} person={p} className="w-7 h-7 text-[10px]" />)}</div>
        )}
        <div className="text-xs text-stone-500">
          {full ? "Full" : t.players.length === 0 ? "Book up to 4 players" : `${t.open} ${t.open === 1 ? "spot" : "spots"} open · join group`}
        </div>
      </div>
      {!full && <Chip tone={t.players.length === 0 ? "club" : "gold"}>{t.players.length === 0 ? "Book" : "Join"}</Chip>}
    </button>
  );
}

function BookingSheet({ slot, course, dateLabel, holes, onClose }) {
  const [done, setDone] = useState(false);
  const me = { name: `${window.CLUB.member.first} ${window.CLUB.member.last}`, initials: window.CLUB.member.initials };
  const [transport, setTransport] = useState("cart");
  const [hole, setHole] = useState(holes);
  const group = [me, ...slot.players];
  const emptySlots = Math.max(0, 4 - group.length);
  return (
    <div className="fixed inset-0 z-50 flex items-end justify-center">
      <div className="absolute inset-0 bg-black/40" onClick={onClose} />
      <div className="relative w-full max-w-[440px] bg-white rounded-t-3xl p-5 pb-7 shadow-2xl">
        <div className="mx-auto w-10 h-1.5 bg-stone-200 rounded-full mb-4" />
        {done ? (
          <div className="text-center py-6">
            <div className="w-16 h-16 rounded-full bg-emerald-50 text-emerald-600 grid place-items-center mx-auto"><Icon name="check" className="w-9 h-9" /></div>
            <div className="text-lg font-semibold text-stone-800 mt-4">Tee time requested</div>
            <div className="text-sm text-stone-500 mt-1">{course.name} · {dateLabel} · {slot.h}:{slot.m} {slot.ap}</div>
            <button onClick={onClose} className="mt-6 w-full bg-club-700 text-white font-semibold rounded-2xl py-3.5">Done</button>
          </div>
        ) : (
          <>
            <div className="flex items-center justify-between">
              <div>
                <div className="text-lg font-semibold text-stone-800">{slot.h}:{slot.m} {slot.ap}</div>
                <div className="text-sm text-stone-500">{course.name} · {dateLabel}</div>
              </div>
              <button onClick={onClose} className="w-9 h-9 rounded-full grid place-items-center text-stone-400 hover:bg-stone-100"><Icon name="close" className="w-5 h-5" /></button>
            </div>

            <div className="mt-5 text-sm font-medium text-stone-700">Your group</div>
            <div className="mt-2 space-y-2">
              {group.map((p, i) => (
                <div key={i} className="flex items-center gap-3 bg-stone-50 rounded-xl px-3 py-2.5">
                  <Avatar person={p} className="w-8 h-8 text-[11px]" />
                  <span className="text-sm font-medium text-stone-700">{p.name}{i === 0 && " (you)"}</span>
                  {p.hcp != null && <span className="ml-auto text-xs text-stone-400">HCP {p.hcp}</span>}
                </div>
              ))}
              {Array.from({ length: emptySlots }).map((_, i) => (
                <button key={i} className="w-full flex items-center gap-3 border border-dashed border-stone-200 rounded-xl px-3 py-2.5 text-stone-400">
                  <span className="w-8 h-8 rounded-full bg-stone-100 grid place-items-center"><Icon name="plus" className="w-4 h-4" /></span>
                  <span className="text-sm">Add player</span>
                </button>
              ))}
            </div>

            <div className="mt-5 flex items-center justify-between">
              <span className="text-sm font-medium text-stone-700">Holes</span>
              <Segmented value={hole} onChange={setHole} options={[{ value: 9, label: "9" }, { value: 18, label: "18" }]} />
            </div>
            <div className="mt-3 flex items-center justify-between">
              <span className="text-sm font-medium text-stone-700">Getting around</span>
              <Segmented value={transport} onChange={setTransport}
                options={[{ value: "cart", label: "Cart" }, { value: "walk", label: "Walk" }, { value: "push", label: "Push cart" }]} />
            </div>

            <button onClick={() => setDone(true)} className="mt-6 w-full bg-club-700 text-white font-semibold rounded-2xl py-3.5 active:scale-[0.99] transition">
              Request tee time
            </button>
          </>
        )}
      </div>
    </div>
  );
}

function GolfScreen({ navigate }) {
  const golf = window.CLUB.golf;
  const days = useMemo(dayStrip, []);
  const [courseId, setCourseId] = useState(golf.courses[0].id);
  const [dateIdx, setDateIdx] = useState(0);
  const [period, setPeriod] = useState("all");
  const [holes, setHoles] = useState(18);
  const [slot, setSlot] = useState(null);

  const course = golf.courses.find((c) => c.id === courseId);
  const day = days[dateIdx];
  const all = useMemo(() => genTeeTimes(courseId, day.key), [courseId, day.key]);
  const list = all.filter((t) => period === "all" || t.period === period);
  const periods = [["all", "All"], ["morning", "Morning"], ["midday", "Midday"], ["afternoon", "Afternoon"]];

  return (
    <div className="pb-24">
      <header className="flex items-center gap-2 px-3 pt-6 pb-2">
        <button onClick={() => navigate("home")} className="w-10 h-10 rounded-full grid place-items-center text-stone-600 hover:bg-stone-100"><Icon name="back" /></button>
        <div><div className="text-[17px] font-semibold text-stone-800">Golf · Tee times</div>
          <div className="text-xs text-stone-400">{course.note}</div></div>
      </header>

      <div className="px-5 pt-2"><Segmented value={courseId} onChange={setCourseId}
        options={golf.courses.map((c) => ({ value: c.id, label: c.name }))} /></div>

      {/* date strip */}
      <div className="flex gap-2 overflow-x-auto px-5 py-4 no-scrollbar">
        {days.map((d) => (
          <button key={d.idx} onClick={() => setDateIdx(d.idx)}
            className={`shrink-0 w-12 py-2 rounded-2xl text-center transition ${d.idx === dateIdx ? "bg-club-700 text-white shadow-sm" : "bg-stone-100 text-stone-500"}`}>
            <div className="text-[11px]">{d.wd}</div><div className="text-base font-semibold">{d.day}</div>
          </button>
        ))}
      </div>

      {/* period filter + holes preference */}
      <div className="flex items-center gap-2 overflow-x-auto px-5 pb-3 no-scrollbar">
        {periods.map(([v, l]) => (
          <button key={v} onClick={() => setPeriod(v)}
            className={`shrink-0 px-3.5 py-1.5 rounded-full text-sm font-medium transition ${period === v ? "bg-club-50 text-club-700" : "bg-stone-100 text-stone-500"}`}>{l}</button>
        ))}
      </div>

      <div className="px-5 space-y-2.5">
        {list.map((t) => <TeeTimeCard key={t.id} t={t} onSelect={setSlot} />)}
      </div>

      {slot && <BookingSheet slot={slot} course={course} dateLabel={`${day.wd} ${day.day}`} holes={holes} onClose={() => setSlot(null)} />}
    </div>
  );
}

/* ============================ ROOT ============================ */
function App() {
  const [route, setRoute] = useState({ name: "home" });
  const navigate = (name) => setRoute({ name });
  return (
    <div className="max-w-[440px] mx-auto min-h-screen bg-white shadow-xl relative">
      {route.name === "home" && <HomeScreen navigate={navigate} />}
      {route.name === "golf" && <GolfScreen navigate={navigate} />}
      <BottomNav navigate={navigate} active={route.name === "home" ? "Home" : ""} />
    </div>
  );
}

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