/* global React, ReactDOM */

const ROUTES = ["home", "house", "gallery", "listowel", "book", "contact", "privacy", "terms"];
const GUIDE_ROUTES = [
  "listowel-accommodation",
  "townhouse-accommodation-listowel",
  "wedding-accommodation-listowel",
  "photo-shoot-location-listowel",
  "family-accommodation-listowel",
  "group-accommodation-listowel",
  "self-catering-accommodation-listowel",
  "things-to-do-in-listowel",
  "day-trips-from-listowel",
  "ballybunion-beach-from-listowel",
  "wild-atlantic-way-base-listowel",
  "ballybunion-golf-accommodation",
];
const ALL_ROUTES = [...ROUTES, ...GUIDE_ROUTES];

const PAGE_META = {
  home: {
    title: "59 William Street Listowel | Luxury Townhouse Stay in County Kerry",
    description: "59 William Street is a restored luxury townhouse in the heart of Listowel, County Kerry, with four bedrooms, five beds, 2.5 bathrooms and direct booking enquiries for short stays.",
  },
  house: {
    title: "The House | 59 William Street Listowel Townhouse",
    description: "Explore the four bedrooms, five beds, 2.5 bathrooms, kitchen and living spaces at 59 William Street, a restored townhouse in central Listowel.",
  },
  gallery: {
    title: "Gallery | 59 William Street Listowel",
    description: "View photos of 59 William Street, including the living room, kitchen, bedrooms, bathrooms and central Listowel setting.",
  },
  listowel: {
    title: "Listowel, County Kerry | Stay at 59 William Street",
    description: "Stay in the heart of Listowel with cafes, pubs, shops, heritage attractions, Ballybunion and the Wild Atlantic Way within easy reach.",
  },
  book: {
    title: "Book Direct | 59 William Street Listowel",
    description: "Check availability and send a direct stay enquiry for 59 William Street, a private four-bedroom townhouse in Listowel, County Kerry.",
  },
  contact: {
    title: "Contact | 59 William Street Listowel",
    description: "Contact 59 William Street for stay enquiries, availability questions and direct booking requests in Listowel, County Kerry.",
  },
  privacy: {
    title: "Privacy Policy | 59 William Street",
    description: "Privacy information for guests and enquiries at 59 William Street, Listowel.",
  },
  terms: {
    title: "Terms and Conditions | 59 William Street",
    description: "Terms and conditions for stay enquiries and guest information at 59 William Street, Listowel.",
  },
  "listowel-accommodation": {
    title: "Listowel Accommodation | 59 William Street Townhouse Stay",
    description: "Stay at 59 William Street, a restored four-bedroom townhouse in central Listowel, Co. Kerry, with direct stay enquiries for short breaks and group stays.",
  },
  "townhouse-accommodation-listowel": {
    title: "Townhouse Accommodation in Listowel | 59 William Street",
    description: "A private whole-house townhouse stay in the heart of Listowel with elegant interiors, kitchen, dining room, living room and space for up to 10 guests.",
  },
  "wedding-accommodation-listowel": {
    title: "Wedding Accommodation in Listowel | 59 William Street",
    description: "Elegant wedding guest accommodation and bridal morning space in central Listowel, County Kerry, with four bedrooms, refined interiors and direct enquiries.",
  },
  "photo-shoot-location-listowel": {
    title: "Photo Shoot Location in Listowel | 59 William Street",
    description: "Book 59 William Street as a stylish Listowel photo shoot location for wedding mornings, editorial shoots, brand content, interiors and private filming enquiries.",
  },
  "family-accommodation-listowel": {
    title: "Family Accommodation in Listowel | 59 William Street",
    description: "Private family accommodation in central Listowel for up to 10 guests, with four bedrooms, five beds, a kitchen and 2.5 bathrooms.",
  },
  "group-accommodation-listowel": {
    title: "Group Accommodation in Listowel | 59 William Street",
    description: "Stay together in a private four-bedroom Listowel townhouse for up to 10 guests, with shared living, dining and kitchen spaces.",
  },
  "self-catering-accommodation-listowel": {
    title: "Self-Catering Accommodation Listowel | 59 William Street",
    description: "Self-catering accommodation in central Listowel with a fully equipped kitchen, dining room, four bedrooms and direct stay enquiries.",
  },
  "things-to-do-in-listowel": {
    title: "Things to Do in Listowel | Local Guide from 59 William Street",
    description: "Explore Listowel cafés, pubs, heritage streets, local shops, walks and nearby Kerry day trips from a central stay at 59 William Street.",
  },
  "day-trips-from-listowel": {
    title: "Day Trips from Listowel | North Kerry Travel Guide",
    description: "Plan day trips from Listowel to Ballybunion, Tralee, Dingle, Castlegregory and the Wild Atlantic Way from 59 William Street.",
  },
  "ballybunion-beach-from-listowel": {
    title: "Ballybunion Beach from Listowel | Stay at 59 William Street",
    description: "Visit Ballybunion Beach and cliffs from a central Listowel townhouse, around 30 minutes away by car, with space for up to 10 guests.",
  },
  "wild-atlantic-way-base-listowel": {
    title: "Wild Atlantic Way Base in Listowel | Stay at 59 William Street",
    description: "Use Listowel as a comfortable townhouse base for Ballybunion, Fenit, Tralee, Dingle and Wild Atlantic Way day trips from 59 William Street.",
  },
  "ballybunion-golf-accommodation": {
    title: "Accommodation Near Ballybunion Golf Club | 59 William Street",
    description: "Stay around 30 minutes from Ballybunion Golf Club in a private Listowel townhouse with four bedrooms, five beds, 2.5 bathrooms and direct enquiries.",
  },
};

const ROOM_META = {
  "bedroom-1-orange": ["Bedroom 1 Orange Room | 59 William Street", "See the Orange Room, a warm double bedroom inside 59 William Street in central Listowel."],
  "bedroom-2-red": ["Bedroom 2 Red Room | 59 William Street", "See the Red Room, a cosy double bedroom inside 59 William Street in central Listowel."],
  "bedroom-3-green": ["Bedroom 3 Green Room | 59 William Street", "See the Green Room, a calm double bedroom inside 59 William Street in central Listowel."],
  "bedroom-4-twin": ["Bedroom 4 Twin Room | 59 William Street", "See the flexible Twin Room for families and groups staying at 59 William Street in Listowel."],
  bathrooms: ["Bathrooms | 59 William Street Listowel", "Explore the 2.5 bathroom spaces arranged across the townhouse at 59 William Street."],
  "living-room": ["Living Room 1 | 59 William Street Listowel", "Explore the cosy TV lounge at 59 William Street, a private townhouse stay in Listowel."],
  "living-room-2": ["Living Room 2 | 59 William Street Listowel", "Explore the open-plan second living area beside the dining room and kitchen at 59 William Street."],
  "dining-room": ["Dining Room | 59 William Street Listowel", "See the dining room and open-plan gathering space at 59 William Street in Listowel."],
  kitchen: ["Kitchen | 59 William Street Listowel", "Explore the fully equipped self-catering kitchen at 59 William Street in central Listowel."],
};

function pageFromLocation() {
  const hashRoute = window.location.hash.replace(/^#\/?/, "");
  if (hashRoute) {
    if (hashRoute.startsWith("room/")) return `room:${hashRoute.slice(5)}`;
    if (hashRoute.startsWith("room:")) return hashRoute;
    return ALL_ROUTES.includes(hashRoute) ? hashRoute : "home";
  }

  const raw = window.location.pathname.replace(/^\/+|\/+$/g, "") || "home";
  if (raw.startsWith("room/")) return `room:${raw.slice(5)}`;
  if (raw.startsWith("room:")) return raw;
  return ALL_ROUTES.includes(raw) ? raw : "home";
}

function pathForPage(page) {
  if (page === "home") return "/";
  if (page.startsWith("room:")) return `/room/${page.slice(5)}`;
  return `/${page}`;
}

function setMetaTag(selector, attribute, value) {
  const tag = document.querySelector(selector);
  if (tag) tag.setAttribute(attribute, value);
}

function updatePageMeta(page) {
  const roomMeta = page.startsWith("room:") ? ROOM_META[page.slice(5)] : null;
  const meta = roomMeta ? { title: roomMeta[0], description: roomMeta[1] } : (PAGE_META[page] || PAGE_META.home);
  const canonicalPath = pathForPage(page);
  const canonicalUrl = `https://59williamstreet.com${canonicalPath}`;
  document.title = meta.title;
  setMetaTag('meta[name="description"]', "content", meta.description);
  setMetaTag('link[rel="canonical"]', "href", canonicalUrl);
  setMetaTag('meta[property="og:url"]', "content", canonicalUrl);
  setMetaTag('meta[property="og:title"]', "content", meta.title);
  setMetaTag('meta[property="og:description"]', "content", meta.description);
  setMetaTag('meta[name="twitter:title"]', "content", meta.title);
  setMetaTag('meta[name="twitter:description"]', "content", meta.description);
}

function App() {
  const [page, setPage] = React.useState(pageFromLocation);
  const [toast, setToast] = React.useState(null);

  const onNavigate = (p) => {
    const nextPath = pathForPage(p);
    if (window.location.pathname !== nextPath || window.location.hash) {
      window.history.pushState({}, "", nextPath);
    }
    setPage(p);
    window.scrollTo({ top: 0, behavior: "instant" });
  };

  React.useEffect(() => {
    const syncPage = () => {
      if (window.location.hash) {
        const pageFromHash = pageFromLocation();
        window.history.replaceState({}, "", pathForPage(pageFromHash));
      }
      setPage(pageFromLocation());
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("popstate", syncPage);
    syncPage();
    return () => window.removeEventListener("popstate", syncPage);
  }, []);

  React.useEffect(() => {
    updatePageMeta(page);
  }, [page]);

  const onBooked = (reference) => {
    setToast(reference ? `Booking request received, reference ${reference}.` : "Booking request received. We'll confirm by email.");
    setTimeout(() => setToast(null), 4200);
  };

  return (
    <div className="page">
      <Nav currentPage={page} onNavigate={onNavigate} />
      {page === "home" && <HomePage onNavigate={onNavigate} />}
      {page === "house" && <HousePage onNavigate={onNavigate} />}
      {page === "gallery" && <GalleryPage onNavigate={onNavigate} />}
      {page === "listowel" && <ListowelPage onNavigate={onNavigate} />}
      {page === "book" && <BookPage onNavigate={onNavigate} onBooked={onBooked} />}
      {page === "contact" && <ContactPage onNavigate={onNavigate} />}
      {page === "privacy" && <LegalPage type="privacy" onNavigate={onNavigate} />}
      {page === "terms" && <LegalPage type="terms" onNavigate={onNavigate} />}
      {GUIDE_ROUTES.includes(page) && <GuidePage slug={page} onNavigate={onNavigate} />}
      {page.startsWith("room:") && <RoomPage slug={page.slice(5)} onNavigate={onNavigate} />}
      <Footer onNavigate={onNavigate} />

      {toast && (
        <div className="ws-toast">
          <span className="check"><Icon name="check-circle-2" size={20} /></span>
          {toast}
        </div>
      )}
    </div>
  );
}

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