// Villa Mesochori — owners' area. Login-gated admin for site copy, pricing and booking email.
// Prototype note: this is a client-side gate for the demo — production needs a real backend.
const adNS = window.VillaMesochoriDesignSystem_9e1a21;
const { Button: AdButton, Input: AdInput, Card: AdCard, Badge: AdBadge, Toast: AdToast, LucideIcon: AdIcon } = adNS;

const ADMIN_SESSION_KEY = "vm-admin-session"; // unused in server mode

function AdField({ label, k, draft, setDraft, hint, type, multiline }) {
  if (multiline) {
    return (
      <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
        <span style={{ font: "600 14px var(--font-body)", color: "var(--text-heading)" }}>{label}</span>
        <textarea
          value={draft[k]}
          onChange={(e) => setDraft({ ...draft, [k]: e.target.value })}
          rows={3}
          style={{
            font: "var(--type-body)", color: "var(--text-body)", background: "var(--surface-card)",
            border: "1px solid var(--border-strong)", borderRadius: "var(--radius-md)",
            padding: "10px 14px", resize: "vertical",
          }}
        ></textarea>
        {hint ? <span style={{ font: "var(--type-small)", color: "var(--text-muted)" }}>{hint}</span> : null}
      </label>
    );
  }
  return (
    <AdInput
      label={label}
      type={type || "text"}
      value={`${draft[k]}`}
      onChange={(e) => setDraft({ ...draft, [k]: type === "number" ? Number(e.target.value) : e.target.value })}
      hint={hint}
    />
  );
}

function AdminLogin({ onIn }) {
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [err, setErr] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const tryLogin = () => {
    setBusy(true);
    window.VMContent.login(email, password).then((ok) => {
      setBusy(false);
      if (ok) onIn(); else setErr(true);
    });
  };
  return (
    <div style={{ maxWidth: 420, margin: "0 auto", padding: "96px var(--container-pad)" }}>
      <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 24 }}>
        <span style={{ font: "var(--type-eyebrow)", letterSpacing: "var(--tracking-wide)", textTransform: "uppercase", color: "var(--accent)" }}>Owners' area</span>
        <h1 style={{ font: "var(--type-h1)", margin: 0 }}>Sign in</h1>
        <p style={{ font: "var(--type-body)", color: "var(--text-muted)", margin: 0 }}>For Maria &amp; the family — manage the site, prices and bookings.</p>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <AdInput label="Email" type="email" value={email} onChange={(e) => { setEmail(e.target.value); setErr(false); }} placeholder="you@example.com" />
        <AdInput label="Password" type="password" value={password} onChange={(e) => { setPassword(e.target.value); setErr(false); }}
          onKeyDown={(e) => { if (e.key === "Enter") tryLogin(); }} />
        {err && <AdToast tone="danger" title="That didn't match">Check the email and password and try again.</AdToast>}
        <div><AdButton size="lg" onClick={tryLogin} disabled={busy}>{busy ? "Signing in…" : "Sign in"}</AdButton></div>
      </div>
    </div>
  );
}

function AdminPanel({ onHome }) {
  const [signedIn, setSignedIn] = React.useState(() => window.VMContent.isSignedIn());
  const [draft, setDraft] = React.useState(() => window.VMContent.get());
  const [saved, setSaved] = React.useState(false);
  const [saveErr, setSaveErr] = React.useState(false);
  const dirty = JSON.stringify(draft) !== JSON.stringify(window.VMContent.get());

  if (!signedIn) return <AdminLogin onIn={() => { setSignedIn(true); setDraft(window.VMContent.get()); }} />;

  const save = () => {
    setSaveErr(false);
    window.VMContent.set(draft).then(() => {
      setSaved(true);
      setTimeout(() => setSaved(false), 2500);
    }).catch(() => setSaveErr(true));
  };
  const reset = () => {
    window.VMContent.reset().then(() => setDraft(window.VMContent.get())).catch(() => setSaveErr(true));
  };
  const signOut = () => { window.VMContent.signOut(); setSignedIn(false); };

  const sectionH = (eyebrow, title) => (
    <div style={{ display: "flex", flexDirection: "column", gap: 4, marginBottom: 4 }}>
      <span style={{ font: "var(--type-eyebrow)", letterSpacing: "var(--tracking-wide)", textTransform: "uppercase", color: "var(--accent)" }}>{eyebrow}</span>
      <h2 style={{ font: "var(--type-h3)", margin: 0 }}>{title}</h2>
    </div>
  );

  return (
    <div data-screen-label="Owners' area" style={{ maxWidth: 760, margin: "0 auto", padding: "48px var(--container-pad) 0" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 16, marginBottom: 8 }}>
        <div>
          <span style={{ font: "var(--type-eyebrow)", letterSpacing: "var(--tracking-wide)", textTransform: "uppercase", color: "var(--accent)" }}>Owners' area</span>
          <h1 style={{ font: "var(--type-h1)", margin: "8px 0 6px" }}>Manage the site</h1>
          <p style={{ font: "var(--type-body)", color: "var(--text-muted)", margin: 0, maxWidth: 520 }}>
            Changes go live on the site the moment you save. Booking requests arrive at the email below.
          </p>
        </div>
        <AdButton variant="ghost" size="sm" onClick={signOut}>Sign out</AdButton>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 40, margin: "32px 0 0" }}>
        <section style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {sectionH("Bookings", "Pricing & rules")}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <AdField label="Nightly rate" k="nightly" type="number" draft={draft} setDraft={setDraft} hint={`Base rate — seasons below can override it`} />
            <AdField label="Cleaning fee" k="cleaning" type="number" draft={draft} setDraft={setDraft} />
            <AdField label="Deposit %" k="depositPct" type="number" draft={draft} setDraft={setDraft} hint="To hold the dates" />
            <AdField label="Minimum nights" k="minNights" type="number" draft={draft} setDraft={setDraft} />
            <AdField label="Check-in from" k="checkIn" draft={draft} setDraft={setDraft} />
            <AdField label="Check-out by" k="checkOut" draft={draft} setDraft={setDraft} />
          </div>
        </section>

        <section style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {sectionH("Guests", "Guest book")}
          <window.VMAdminExtras.GuestBook />
        </section>

        <section style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {sectionH("Availability", "Google Calendar sync")}
          <window.VMAdminExtras.CalendarSync />
        </section>

        <section style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {sectionH("Bookings", "Seasonal pricing")}
          <window.VMAdminExtras.SeasonPricing draft={draft} setDraft={setDraft} />
        </section>

        <section style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {sectionH("Photos", "Site photos")}
          <window.VMAdminExtras.PhotoManager draft={draft} setDraft={setDraft} />
        </section>

        <section style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {sectionH("Photos", "More photos gallery")}
          <window.VMAdminExtras.GalleryEditor draft={draft} setDraft={setDraft} />
        </section>

        <section style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {sectionH("Payments", "Deposits — PayPal & Square")}
          <p style={{ font: "var(--type-small)", color: "var(--text-muted)", margin: 0 }}>
            Guests pay the {draft.depositPct}% deposit right after sending their booking request. Set up either or both — PayPal shows its buttons, Square adds a card form.
          </p>
          <AdField label="PayPal Client ID" k="paypalClientId" draft={draft} setDraft={setDraft} hint="From a free PayPal Business account: developer.paypal.com → Apps & Credentials → Create App → copy the Live Client ID. Leave empty to skip PayPal." />
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <AdField label="Square Application ID" k="squareAppId" draft={draft} setDraft={setDraft} hint="developer.squareup.com → your app → Production → Application ID" />
            <AdField label="Square Location ID" k="squareLocationId" draft={draft} setDraft={setDraft} hint="Square Dashboard → Locations" />
          </div>
          <window.VMAdminExtras.SquareSecrets />
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <AdField label="Payment currency code" k="payCurrency" draft={draft} setDraft={setDraft} hint="EUR, AUD or USD — must match the symbol below" />
            <AdField label="Currency symbol" k="currency" draft={draft} setDraft={setDraft} hint="Shown next to prices on the site" />
          </div>
        </section>

        <section style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {sectionH("Where requests go", "Booking email")}
          <AdField label="Email address" k="email" type="email" draft={draft} setDraft={setDraft} hint="Guests' booking requests open an email to this address with their dates and details filled in" />
        </section>

        <section style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {sectionH("Home page", "Copy")}
          <AdField label="Hero headline" k="heroTitle" draft={draft} setDraft={setDraft} multiline />
          <AdField label="Hero subtitle" k="heroSub" draft={draft} setDraft={setDraft} multiline />
          <AdField label="Highlights row" k="homeHighlights" draft={draft} setDraft={setDraft} multiline hint="One per line: icon | title | text. Icon names from lucide.dev (e.g. key-round, mountain, car)." />
          <AdField label="The house — heading" k="houseTitle" draft={draft} setDraft={setDraft} />
          <AdField label="The house — first paragraph" k="houseBody1" draft={draft} setDraft={setDraft} multiline />
          <AdField label="The house — second paragraph" k="houseBody2" draft={draft} setDraft={setDraft} multiline />
          <window.VMAdminExtras.HouseCardsEditor draft={draft} setDraft={setDraft} />
          <AdField label="Bedrooms — heading" k="bedsTitle" draft={draft} setDraft={setDraft} />
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <AdField label="Double room — title" k="bedDoubleTitle" draft={draft} setDraft={setDraft} />
            <AdField label="Twin room — title" k="bedTwinTitle" draft={draft} setDraft={setDraft} />
          </div>
          <AdField label="Double room — text" k="bedDoubleBody" draft={draft} setDraft={setDraft} multiline />
          <AdField label="Twin room — text" k="bedTwinBody" draft={draft} setDraft={setDraft} multiline />
          <AdField label="The view — heading" k="viewTitle" draft={draft} setDraft={setDraft} />
          <AdField label="The view — text" k="viewBody" draft={draft} setDraft={setDraft} multiline />
          <AdField label="Handwritten host note" k="hostNote" draft={draft} setDraft={setDraft} hint="The pencilled aside in 'The view' section" />
          <AdField label="Amenities — heading" k="amenTitle" draft={draft} setDraft={setDraft} />
          <AdField label="Amenities list" k="amenities" draft={draft} setDraft={setDraft} multiline hint="One per line: icon | text. Icon names from lucide.dev." />
          <AdField label="The village — heading" k="villageTitle" draft={draft} setDraft={setDraft} />
          <AdField label="The village — first paragraph" k="villageBody1" draft={draft} setDraft={setDraft} multiline />
          <AdField label="The village — second paragraph" k="villageBody2" draft={draft} setDraft={setDraft} multiline />
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <AdField label="Closing invitation — title" k="ctaTitle" draft={draft} setDraft={setDraft} />
          </div>
          <AdField label="Closing invitation — text" k="ctaBody" draft={draft} setDraft={setDraft} multiline />
        </section>

        <section style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {sectionH("Getting here", "Directions to the house")}
          <AdField label="Page heading" k="arriveTitle" draft={draft} setDraft={setDraft} />
          <AdField label="Intro text" k="arriveIntro" draft={draft} setDraft={setDraft} multiline />
          <AdField label="Address line" k="arriveAddress" draft={draft} setDraft={setDraft} hint="Shown next to the 'Open in Google Maps' button" />
          <window.VMAdminExtras.ArrivalEditor draft={draft} setDraft={setDraft} />
        </section>

        <section style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {sectionH("Places to go", "Guide intro")}
          <AdField label="Guide heading" k="guideTitle" draft={draft} setDraft={setDraft} />
          <AdField label="Guide intro" k="guideIntro" draft={draft} setDraft={setDraft} multiline />
          <window.VMAdminExtras.PlacesEditor draft={draft} setDraft={setDraft} />
        </section>

        <div style={{ display: "flex", gap: 12, alignItems: "center", padding: "20px 0 0", borderTop: "1px solid var(--border-soft)" }}>
          <AdButton size="lg" onClick={save} disabled={!dirty}>Save changes</AdButton>
          <AdButton variant="secondary" onClick={onHome}>View the site</AdButton>
          <AdButton variant="ghost" onClick={reset}>Reset to defaults</AdButton>
          {saved && <AdBadge tone="success">Saved — live on the site</AdBadge>}
          {saveErr && <AdBadge tone="danger">Couldn't save — check your connection and try again</AdBadge>}
        </div>
        <p style={{ font: "var(--type-small)", color: "var(--text-muted)", margin: "0 0 8px" }}>
          {window.VMContent.serverMode()
            ? "Connected to the server — saved changes appear for every visitor."
            : "Prototype note: no server connected, so changes are saved in this browser only. On the live site (with api.php uploaded) they appear for every visitor."}
        </p>
      </div>
    </div>
  );
}

window.VMAdmin = AdminPanel;
