// app.jsx — root: routing between dashboard / public booking / confirmation + tweaks

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "industry": "generic"
}/*EDITMODE-END*/;

const INDUSTRY_OPTIONS = [
  { id: "generic", label: "Generic" },
  { id: "classes", label: "Classes" },
  { id: "hair",    label: "Hairdresser" },
  { id: "nails",   label: "Nail bar" },
  { id: "beauty",  label: "Beauty salon" },
  { id: "pool",    label: "Swimming pool" },
];

// ── Public booking page (no auth needed) ─────────────────────
function PublicBookingApp({ slug }) {
  const [state, setState] = React.useState("loading"); // loading | ready | notfound
  const [pubData, setPubData]   = React.useState(null);
  const [booking, setBooking]   = React.useState(null);
  const [confirmed, setConfirmed] = React.useState(false);
  const { actions } = useAppData();

  React.useEffect(() => {
    fetchPublicData(slug).then(d => {
      if (!d) setState("notfound");
      else { setPubData(d); setState("ready"); }
    });
  }, [slug]);

  if (state === "loading") return <LoadingShell/>;
  if (state === "notfound") return (
    <div className="login-shell">
      <div className="login-card" style={{textAlign:"center"}}>
        <div className="sb-mark" style={{margin:"0 auto 16px"}}>N</div>
        <h2>Booking page not found</h2>
        <p style={{color:"var(--text-muted)", marginTop:8}}>This link may be incorrect or the business is no longer active.</p>
      </div>
    </div>
  );

  if (confirmed) return (
    <div style={getBrandStyle(pubData.profile)}>
      <Confirmation booking={booking} profile={pubData.profile}
        onBack={() => window.location.reload()}
        onAnother={() => { setConfirmed(false); setBooking(null); }}/>
    </div>
  );

  return (
    <div style={getBrandStyle(pubData.profile)}>
      <BookingPage
        data={pubData}
        onBack={() => window.location.reload()}
        onConfirmed={(b) => {
          // write booking directly with business owner's userId
          const bookId      = uid("book");
          const manageToken = (typeof crypto !== "undefined" && crypto.randomUUID) ? crypto.randomUUID() : uid("tok");
          const events = pubData.events || [];
          const event  = events.find(e => e.id === b.eventId) || events[0];
          const next   = {
            id: bookId, date: b.date, time: b.time,
            eventId: event?.id, eventName: event?.name,
            guestName: b.name, guestEmail: b.email,
            guestPhone: b.phone || "", notes: b.notes || "",
            answers: b.answers || {}, location: event?.location || "",
            paymentStatus: b.paymentStatus || (Number(event?.price||0)>0?"Paid":"Not required"),
            paymentProvider: b.paymentProvider || "",
            paymentAmount: b.paymentAmount ?? Number(event?.price||0),
            status: "Confirmed", source: "Public page",
            manageToken,
            couponCode:     b.couponCode     || "",
            discountApplied: b.discountApplied || 0,
          };
          // update local capacity immediately
          setPubData(d => ({ ...d, bookings: [next, ...d.bookings] }));
          // persist to Supabase
          sb.from("bookings").insert({
            id: bookId, user_id: pubData.userId,
            event_id: next.eventId, event_name: next.eventName,
            date: next.date, time: next.time,
            guest_name: next.guestName, guest_email: next.guestEmail, guest_phone: next.guestPhone,
            notes: next.notes, answers: next.answers, location: next.location,
            status: next.status, payment_status: next.paymentStatus,
            payment_provider: next.paymentProvider, payment_amount: next.paymentAmount, source: next.source,
            manage_token: manageToken,
            coupon_code: next.couponCode || null,
            discount_applied: next.discountApplied || 0,
          });
          // Fire-and-forget: emails + coupon usage increment
          sendBookingEmail("guest_confirmation", next, pubData.profile);
          sendBookingEmail("owner_notification", next, pubData.profile);
          if (b.couponId) incrementCouponUsage(b.couponId);
          setBooking(next);
          setConfirmed(true);
        }}
      />
    </div>
  );
}

// ── Loading screen ────────────────────────────────────────────
function LoadingShell() {
  return (
    <div className="loading-shell">
      <div className="loading-dots">
        <span/><span/><span/>
      </div>
    </div>
  );
}

// ── Main admin app (requires auth) ────────────────────────────
function App() {
  // ALL hooks must be at the top — no hooks after conditional returns
  const [t, setTweak]               = useTweaks(TWEAK_DEFAULTS);
  const { data, authUser, actions } = useAppData();
  const [view, setView]             = React.useState("dashboard");
  const [active, setActive]         = React.useState("overview");
  const [booking, setBooking]       = React.useState(null);
  const [copied, setCopied]         = React.useState(false);
  const [impersonated, setImpersonated] = React.useState(null); // { data } when viewing another account
  const bookSlug    = React.useMemo(() => new URLSearchParams(window.location.search).get("book"), []);
  const manageToken = React.useMemo(() => new URLSearchParams(window.location.search).get("manage"), []);

  // detect ?manage=token → customer manage their booking (no auth needed)
  if (manageToken) return <ManageBookingPage token={manageToken}/>;

  // detect ?book=slug → show public booking page (no auth needed)
  if (bookSlug) return <PublicBookingApp slug={bookSlug}/>;

  // still checking auth state
  if (authUser === undefined) return <LoadingShell/>;

  // not logged in
  if (!authUser) return <LoginPage/>;

  // authenticated but data still loading from Supabase
  if (!data) return <LoadingShell/>;

  // account suspended by super admin
  if (data.profile.suspended) return (
    <div className="suspension-screen">
      <div className="suspension-card">
        <div className="sb-mark" style={{margin:"0 auto 16px",background:"var(--danger)"}}>!</div>
        <h2>Account suspended</h2>
        <p>This account has been suspended. Please contact <a href="mailto:hello@nexusbookings.app">hello@nexusbookings.app</a> for more information.</p>
        <button className="btn ghost" style={{marginTop:12}} onClick={() => sb.auth.signOut()}>Sign out</button>
      </div>
    </div>
  );

  const presetByBusiness = { classes: "classes", pool_hire: "pool", beauty: "beauty", nails: "nails" };
  const industryKey = presetByBusiness[data.profile.businessType] || t.industry;
  const industry    = PRESETS[industryKey] || PRESETS.generic;

  const onCopy = () => {
    const url = `${window.location.origin}/?book=${data.profile.bookingUrl}`;
    navigator.clipboard?.writeText(url).catch(()=>{});
    setCopied(true);
    setTimeout(() => setCopied(false), 1800);
  };

  const signOut = () => sb.auth.signOut();

  const onViewAccount = async (userId) => {
    const accountData = await fetchUserData(userId);
    if (accountData) { setImpersonated(accountData); setActive("overview"); }
  };

  if (impersonated) {
    const impIndustry = PRESETS[impersonated.profile?.businessType] || PRESETS.generic;
    return (
      <div className="workspace" style={getBrandStyle(impersonated.profile)}>
        <div className="impersonate-banner">
          <span>👁 Viewing <strong>{impersonated.profile.brandName || impersonated.profile.email || "account"}</strong> as super admin</span>
          <button onClick={() => { setImpersonated(null); setActive("platform"); }}>← Exit to Platform</button>
        </div>
        <Sidebar
          active={active} onNav={setActive}
          onOpenBooking={() => {}} onOpenAdmin={() => {}}
          profile={impersonated.profile} copied={false} onCopy={() => {}}
          onSignOut={() => { setImpersonated(null); setActive("platform"); }}
        />
        <main className="main" style={{paddingTop:40}}>
          <Dashboard active={active} industry={impIndustry} data={impersonated} actions={{
            addBooking:()=>{}, updateBookingStatus:()=>{}, rescheduleBooking:()=>{},
            saveEvent:()=>{}, toggleEvent:()=>{}, deleteEvent:()=>{},
            saveAvailability:()=>{}, addBlockedTime:()=>{}, removeBlockedTime:()=>{},
            connectIntegration:()=>{}, disconnectIntegration:()=>{},
            updateProfile:()=>{}, updateNotifications:()=>{},
          }} onOpenBooking={() => {}} onViewAccount={() => {}}/>
        </main>
      </div>
    );
  }

  if (view === "booking") {
    return (
      <div style={getBrandStyle(data.profile)}>
        <BookingPage
          data={data}
          onBack={() => setView("dashboard")}
          onConfirmed={(b) => { setBooking(actions.addBooking(b)); setView("confirmed"); }}
        />
        <TweaksUI t={t} setTweak={setTweak}/>
      </div>
    );
  }
  if (view === "confirmed") {
    return (
      <div style={getBrandStyle(data.profile)}>
        <Confirmation booking={booking} profile={data.profile}
          onBack={() => setView("dashboard")}
          onAnother={() => setView("booking")}/>
        <TweaksUI t={t} setTweak={setTweak}/>
      </div>
    );
  }
  if (view === "admin") {
    return <AdminShell data={data} actions={actions} onBack={() => setView("dashboard")}/>;
  }

  return (
    <div className="workspace" style={getBrandStyle(data.profile)}>
      <Sidebar
        active={active} onNav={setActive}
        onOpenBooking={() => setView("booking")}
        onOpenAdmin={() => setView("admin")}
        profile={data.profile} copied={copied} onCopy={onCopy}
        onSignOut={signOut}
      />
      <main className="main">
        <Dashboard
          active={active} industry={industry} data={data} actions={actions}
          onOpenBooking={() => setView("booking")}
          onViewAccount={onViewAccount}
        />
        <button onClick={() => setView("booking")} className="floating-preview"
          style={{ position:"fixed", bottom:20, zIndex:5, background:"var(--accent)", color:"var(--secondary)",
            border:0, borderRadius:10, padding:"10px 14px", fontSize:12.5, fontWeight:600,
            display:"inline-flex", alignItems:"center", gap:8, boxShadow:"0 4px 14px rgba(0,0,0,.15)" }}
          title="Preview the public booking page">
          <I.arrow size={14}/> View booking page
        </button>
      </main>
      {copied && <div className="toast"><I.check size={14}/> Booking link copied to clipboard</div>}
      <TweaksUI t={t} setTweak={setTweak}/>
    </div>
  );
}


function TweaksUI({ t, setTweak }) {
  return (
    <TweaksPanel>
      <TweakSection label="Industry preset"/>
      <TweakSelect
        label="Vertical"
        value={t.industry}
        options={INDUSTRY_OPTIONS.map(o => ({ value: o.id, label: o.label }))}
        onChange={(v) => setTweak('industry', v)}
      />
      <div style={{fontSize:11, color:"rgba(41,38,27,.55)", lineHeight:1.4, marginTop:2}}>
        Swaps services, demo bookings, and the public page's headline service.
      </div>
    </TweaksPanel>
  );
}

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