// T's Cottage - Premium React & TypeScript Web Application
// Fully functional interactive system with local storage persistence and state-based routing

const { useState, useEffect, useRef } = (window as any).React;

// --- TYPE DEFINITIONS ---
interface PropertyDetails {
  title: string;
  description: string;
  baseRate: number;
  cleaningFee: number;
  taxRate: number;
  amenities: {
    wifi: boolean;
    hottub: boolean;
    fireplace: boolean;
    dock: boolean;
    kayaks: boolean;
    kitchen: boolean;
  };
}

interface Booking {
  id: string;
  guestName: string;
  guestEmail: string;
  checkIn: string;
  checkOut: string;
  guestsCount: number;
  totalPrice: number;
  status: 'Pending' | 'Approved' | 'Denied';
  createdDate: string;
}

interface SyncChannel {
  id: string;
  name: string;
  url: string;
  lastSynced: string;
  status: 'Success' | 'Syncing' | 'Failed';
}

interface BlockedRange {
  start: Date;
  end: Date;
  source: string;
}

// --- DEFAULT INITIAL SEED DATA ---
const DEFAULT_PROPERTY: PropertyDetails = {
  title: "T's Lakeside Wood Cabin & Spa",
  description: "Tucked away in a pristine pine forest overlooking a private serene lake, T's Cottage is a masterpiece of modern-rustic craftsmanship. Combining natural cedar structures with high-end glassmorphism and state-of-the-art amenities, this short-term rental offers the ultimate escape for those seeking nature without compromising on premium comfort.",
  baseRate: 350,
  cleaningFee: 120,
  taxRate: 0.12,
  amenities: {
    wifi: true,
    hottub: true,
    fireplace: true,
    dock: true,
    kayaks: true,
    kitchen: true
  }
};

const DEFAULT_BOOKINGS: Booking[] = [
  {
    id: "B-9831",
    guestName: "Evelyn Carter",
    guestEmail: "evelyn.c@luxetravel.com",
    checkIn: "2026-06-05",
    checkOut: "2026-06-10",
    guestsCount: 2,
    totalPrice: 2094.40,
    status: "Approved",
    createdDate: "2026-05-18"
  },
  {
    id: "B-5421",
    guestName: "Marcus Sterling",
    guestEmail: "msterling@ventures.co",
    checkIn: "2026-06-18",
    checkOut: "2026-06-22",
    guestsCount: 4,
    totalPrice: 1702.40,
    status: "Pending",
    createdDate: "2026-05-22"
  },
  {
    id: "B-1290",
    guestName: "Juliet Vance",
    guestEmail: "juliet.vance@designloft.io",
    checkIn: "2026-05-02",
    checkOut: "2026-05-05",
    guestsCount: 2,
    totalPrice: 1310.40,
    status: "Denied",
    createdDate: "2026-04-15"
  }
];

const DEFAULT_CHANNELS: SyncChannel[] = [
  {
    id: "sync-airbnb",
    name: "Airbnb Sync",
    url: "https://www.airbnb.com/calendar/sync/1202057271588637330.ics",
    lastSynced: "2026-05-23 15:45",
    status: "Success"
  },
  {
    id: "sync-vrbo",
    name: "VRBO Channel",
    url: "https://www.vrbo.com/calendar/ical/8342751.ics",
    lastSynced: "2026-05-23 15:40",
    status: "Success"
  }
];

// Blocked date ranges from external channels and approved bookings
const DEFAULT_BLOCKED_DATES: BlockedRange[] = [
  {
    start: new Date(2026, 4, 10), // May 10, 2026
    end: new Date(2026, 4, 14),   // May 14, 2026
    source: "Airbnb Sync"
  },
  {
    start: new Date(2026, 4, 20), // May 20, 2026
    end: new Date(2026, 4, 23),   // May 23, 2026
    source: "VRBO Channel"
  },
  {
    start: new Date(2026, 5, 5),  // June 5, 2026 (From Carter booking)
    end: new Date(2026, 5, 10),
    source: "Local Booking (Approved)"
  }
];

interface Review {
  id: string;
  guestName: string;
  avatarText: string;
  rating: number;
  stayDate: string;
  property: 'hickory' | 'moseywood';
  propertyName: string;
  reviewText: string;
}

const REVIEWS_DATA: Review[] = [
  {
    id: "rev-1",
    guestName: "Sarah J.",
    avatarText: "SJ",
    rating: 5,
    stayDate: "Stayed at Hickory - October 2025",
    property: "hickory",
    propertyName: "Hickory Chalet",
    reviewText: "My husband and I were looking for a relaxing weekend away for our anniversary and that is exactly what we got. The house was private, yet close enough to the restaurants.\n\nWhen it came to communication, Tulika was very quick with responses. Through messages and through a phone call.\n\nWe would definitely be interested in staying again."
  },
  {
    id: "rev-2",
    guestName: "Michael R.",
    avatarText: "MR",
    rating: 5,
    stayDate: "Stayed at Moseywood - January 2026",
    property: "moseywood",
    propertyName: "Moseywood Chalet",
    reviewText: "Tulika was very responsive and very flexible as a host. The outdoor space was amazing, and everything was provided to make the stay ideal. Would recommend to a friend!"
  },
  {
    id: "rev-3",
    guestName: "Evelyn D.",
    avatarText: "ED",
    rating: 5,
    stayDate: "Stayed at Hickory - August 2025",
    property: "hickory",
    propertyName: "Hickory Chalet",
    reviewText: "This was the perfect place for our group. There was so much to do just at the house; fire pit, pickleball court, hot tub, game room! Place was very clean and cozy. Tulika responded immediately with any questions I had throughout the entirety of booking, our stay, and at checkout. I highly recommend!"
  },
  {
    id: "rev-4",
    guestName: "David T.",
    avatarText: "DT",
    rating: 5,
    stayDate: "Stayed at Moseywood - September 2025",
    property: "moseywood",
    propertyName: "Moseywood Chalet",
    reviewText: "We stayed 2 nights for my daughter's birthday. Had a fantastic time. Kids loved the pickleball court. So much to do at the house!"
  },
  {
    id: "rev-5",
    guestName: "Amanda L.",
    avatarText: "AL",
    rating: 5,
    stayDate: "Stayed at Hickory - November 2025",
    property: "hickory",
    propertyName: "Hickory Chalet",
    reviewText: "We had a pleasant stay at Tulika’s place. The property was well-maintained, clean, and as described in the listing. The check-in process was smooth, and communication with the host was clear and responsive throughout our stay. The location was convenient and suited our needs well. Overall, it was a comfortable experience, and we would consider staying here again."
  },
  {
    id: "rev-6",
    guestName: "Robert K.",
    avatarText: "RK",
    rating: 5,
    stayDate: "Stayed at Moseywood - February 2026",
    property: "moseywood",
    propertyName: "Moseywood Chalet",
    reviewText: "Awesome stay! Celebrated my boyfriend’s 30th birthday with friends and family! Was the perfect place to hold it. Tulika was very kind and responsive to me when I had questions or needed help adjusting checkout times! She was super flexible and understanding. The house was beautiful and had so many bedrooms and things included such as the sauna, fire pit, game room, hot tub, etc. It was even dog friendly which was much appreciated! I recommend this place to anyone looking at it!"
  }
];

// Carousel Slides
const CAROUSEL_SLIDES = [
  {
    img: "./assets/images/01-HomeView_Media-45_Hickory_Rd.jpg",
    title: "The Ultimate Lakeside Sanctuary",
    desc: "Premium natural timber cabin architecture merging beautifully with modern glass windows, shining in the warm ambient lights of dusk."
  },
  {
    img: "./assets/images/04-HomeView_Media-45_Hickory_Rd.jpg",
    title: "Rustic Luxury Living Room",
    desc: "Exposed vaulted cedar ceiling beams, a majestic natural stone fireplace, and premium seating looking out to serene waters."
  },
  {
    img: "./assets/images/11-HomeView_Media-45_Hickory_Rd.jpg",
    title: "Master Loft Suite",
    desc: "Wake up to breathtaking views of misty green forests from a comfortable king bed dressed in rich plush organic linens."
  },
  {
    img: "./assets/images/22-HomeView_Media-45_Hickory_Rd.jpg",
    title: "Private Lakeside Deck & Spa",
    desc: "Submerge in a steaming outdoor wood-integrated hot tub under strings of Edison lights as the sunset paints the sky."
  }
];

// Room Explorer Tabs
const ROOM_EXPLORER_DATA = [
  {
    id: "exterior",
    name: "Exterior View",
    img: "./assets/images/02-HomeView_Media-45_Hickory_Rd.jpg",
    title: "Mastercrafted Timber Architecture",
    desc: "Constructed with Canadian red cedar logs and steel glass framing, T's Cottage stands elegantly by the shore. Features a private floating dock, matching kayak slip, and a large wrap-around deck. Perfect for morning coffees and late-night stargazing over the pristine waters."
  },
  {
    id: "living",
    name: "Living Space",
    img: "./assets/images/06-HomeView_Media-45_Hickory_Rd.jpg",
    title: "Warm hearth, High ceilings",
    desc: "Our high-vaulted living area centers around a hand-laid river rock wood fireplace. Large custom floor-to-ceiling windows wash the space in natural daylight. Complete with premium modern sofas, a Sonos surround system, and a warm selection of classic books and board games."
  },
  {
    id: "bedroom",
    name: "Loft Bedroom",
    img: "./assets/images/12-HomeView_Media-45_Hickory_Rd.jpg",
    title: "Tranquility in the Canopy",
    desc: "Situated in the private top-floor loft, the master bedroom boasts a plush king-size hybrid mattress, luxury organic waffle-knit blankets, copper reading lights, and an oversized triangular picture window overlooking the pine forest canopy. Sleep peacefully in nature's absolute silence."
  },
  {
    id: "deck",
    name: "Spa Deck",
    img: "./assets/images/24-HomeView_Media-45_Hickory_Rd.jpg",
    title: "Outdoor Sunset Hydrotherapy",
    desc: "Step out onto the low-profile lakeside cedar deck to discover our custom-integrated 6-person hot tub. Kept at a soothing 104°F, it features variable hydro jets and ambient LED lights. Sit back, relax, and let the gentle sounds of the forest wash your stress away."
  }
];

// Terms & Conditions data
const TERMS_DATA = [
  {
    title: "1. Booking & Payment Policies",
    content: "To secure your stay at T's Cottage, a 50% deposit is required at the time of booking, with the remaining balance auto-charged 14 days prior to your check-in date. Bookings made within 14 days of arrival must be paid in full. We accept all major credit cards. A refundable security deposit of $300 is held on your card 1 day before arrival and released within 3 business days post check-out, pending a clean property inspection report."
  },
  {
    title: "2. Cancellation & Refund Guidelines",
    content: "We understand that plans change. Our policy is designed to be fair to both guests and our hosting operations:\n- Full Refund (100%): Cancellations made up to 30 days prior to check-in.\n- Partial Refund (50%): Cancellations made between 14 and 30 days prior to check-in.\n- No Refund: Cancellations made within 14 days of check-in.\n*Guests are highly encouraged to purchase comprehensive travel insurance to safeguard against unexpected trip interruptions."
  },
  {
    title: "3. Cottage House Rules & Occupancy",
    content: "We take great pride in maintaining a pristine space. Guests are required to adhere to the following guidelines during their stay:\n- Quiet Hours: Strictly enforced from 10:00 PM to 8:00 AM out of respect for our surrounding woodland neighbors.\n- Maximum Occupancy: Up to 6 guests strictly. Unregistered overnight guests will result in immediate cancellation of stay with no refund.\n- Smoking/Vaping: Absolutely prohibited inside the cottage or on the wooden decks. A $500 deep-cleaning fee applies to violations.\n- Pets: Dogs are considered with prior written host approval and a non-refundable $75 pet fee."
  },
  {
    title: "4. Water Safety & Hot Tub Guidelines",
    content: "Our lakeside location is beautiful but requires safety consciousness:\n- Private Dock & Watercraft: Children must wear life jackets (provided in the dock storage trunk) at all times when on the dock or using kayaks.\n- Spa Pool (Hot Tub): Shower before entering. Keep the temperature under 104°F. Glassware is strictly prohibited in or around the hot tub; please use the provided acrylic glasses. Securely lock the insulated cover on top of the hot tub immediately after use to protect children and retain heat."
  }
];

// --- MAIN REACT APPLICATION COMPONENT ---
function App() {
  // Page routing state
  const [currentPage, setCurrentPage] = useState<'home' | 'admin'>('home');
  const [scrolled, setScrolled] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);

  // Property Details State
  const [property, setProperty] = useState<PropertyDetails>(() => {
    const saved = localStorage.getItem("tscottage_property");
    return saved ? JSON.parse(saved) : DEFAULT_PROPERTY;
  });

  // Bookings list state
  const [bookings, setBookings] = useState<Booking[]>(() => {
    const saved = localStorage.getItem("tscottage_bookings");
    return saved ? JSON.parse(saved) : DEFAULT_BOOKINGS;
  });

  // External Calendar Sync Channels state
  const [channels, setChannels] = useState<SyncChannel[]>(() => {
    const saved = localStorage.getItem("tscottage_channels");
    return saved ? JSON.parse(saved) : DEFAULT_CHANNELS;
  });

  // Blocked Date Ranges State
  const [blockedRanges, setBlockedRanges] = useState<BlockedRange[]>(() => {
    const saved = localStorage.getItem("tscottage_blocked");
    if (saved) {
      // Deserialize dates
      return JSON.parse(saved).map((b: any) => ({
        ...b,
        start: new Date(b.start),
        end: new Date(b.end)
      }));
    }
    return DEFAULT_BLOCKED_DATES;
  });

  // Write changes to localStorage
  useEffect(() => {
    localStorage.setItem("tscottage_property", JSON.stringify(property));
  }, [property]);

  useEffect(() => {
    localStorage.setItem("tscottage_bookings", JSON.stringify(bookings));
    
    // Sync local approved bookings to blocked dates automatically!
    const localApprovedRanges = bookings
      .filter(b => b.status === "Approved")
      .map(b => ({
        start: new Date(b.checkIn + "T00:00:00"),
        end: new Date(b.checkOut + "T23:59:59"),
        source: `Local Booking (${b.guestName})`
      }));
    
    // Keep external synced channel dates as well
    const externalRanges = blockedRanges.filter(r => !r.source.startsWith("Local Booking"));
    
    const combined = [...externalRanges, ...localApprovedRanges];
    setBlockedRanges(combined);
    localStorage.setItem("tscottage_blocked", JSON.stringify(combined));
  }, [bookings]);

  useEffect(() => {
    localStorage.setItem("tscottage_channels", JSON.stringify(channels));
  }, [channels]);

  // Monitor scroll for sticky header blur styling
  useEffect(() => {
    const handleScroll = () => {
      setScrolled(window.scrollY > 40);
    };
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  // Quick helper to scroll to top on nav click
  const navigateTo = (page: 'home' | 'admin') => {
    setCurrentPage(page);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  return (
    <div className="app-layout">
      {/* Premium Navigation Header */}
      <header className={`header-glass ${scrolled ? 'scrolled' : ''}`}>
        <div className="container nav-container">
          <div className="logo" onClick={() => { navigateTo('home'); setMobileMenuOpen(false); }}>
            <i className="fa-solid fa-hotel"></i>
            <span>T's Cottage</span>
          </div>
          
          {/* Mobile Menu Toggler */}
          <button 
            className="mobile-menu-toggle" 
            onClick={() => setMobileMenuOpen(prev => !prev)}
            aria-label="Toggle Navigation Menu"
          >
            <i className={`fa-solid ${mobileMenuOpen ? 'fa-xmark' : 'fa-bars'}`}></i>
          </button>
          
          <ul className={`nav-menu ${mobileMenuOpen ? 'mobile-open' : ''}`}>
            <li>
              <span 
                className={`nav-link ${currentPage === 'home' ? 'active' : ''}`}
                onClick={() => { navigateTo('home'); setMobileMenuOpen(false); }}
                id="nav-home"
              >
                Home
              </span>
            </li>

            <li>
              <span 
                className={`nav-link ${currentPage === 'admin' ? 'active' : ''}`}
                onClick={() => { navigateTo('admin'); setMobileMenuOpen(false); }}
                id="nav-admin"
              >
                Staff Portal
              </span>
            </li>
            <li>
              <button 
                className="btn-premium" 
                onClick={() => {
                  setMobileMenuOpen(false);
                  window.location.href = "https://lakeharmonyrental.guestybookings.com/";
                }}
                id="header-booking-btn"
              >
                Book Now
              </button>
            </li>
          </ul>
        </div>
      </header>

      {/* Pages Container */}
      <main className="main-content">
        {currentPage === 'home' && (
          <HomePage 
            property={property} 
            blockedRanges={blockedRanges}
            onBookNowClick={() => navigateTo('home')}
            bookings={bookings}
            setBookings={setBookings}
          />
        )}


        
        {currentPage === 'admin' && (
          <AdminPortalPage 
            property={property}
            setProperty={setProperty}
            bookings={bookings}
            setBookings={setBookings}
            channels={channels}
            setChannels={setChannels}
            blockedRanges={blockedRanges}
            setBlockedRanges={setBlockedRanges}
          />
        )}
      </main>

      {/* Luxury Footer */}
      <footer>
        <div className="container">
          <div className="footer-grid">
            <div className="footer-col">
              <div className="logo" style={{ marginBottom: '1.25rem' }}>
                <i className="fa-solid fa-hotel"></i>
                <span>T's Cottage</span>
              </div>
              <p style={{ marginBottom: '1.5rem' }}>
                Discover absolute shoreline serenity at our boutique lakeside cabin. Crafted for discerning travelers seeking nature, complete wood finish, heated outdoor hot tub spa, and modern-rustic comfort.
              </p>
              <div className="social-links">
                <a href="#" className="social-icon" aria-label="Instagram"><i className="fa-brands fa-instagram"></i></a>
                <a href="#" className="social-icon" aria-label="Facebook"><i className="fa-brands fa-facebook-f"></i></a>
                <a href="#" className="social-icon" aria-label="Pinterest"><i className="fa-brands fa-pinterest-p"></i></a>
              </div>
            </div>
            
            <div className="footer-col">
              <h4>Quick Links</h4>
              <ul className="footer-links">
                <li><a onClick={() => navigateTo('home')} style={{ cursor: 'pointer' }}>Lakeside Cottage</a></li>
                <li><a onClick={() => navigateTo('admin')} style={{ cursor: 'pointer' }}>Staff Admin Access</a></li>
              </ul>
            </div>
            
            <div className="footer-col">
              <h4>Premium Amenities</h4>
              <ul className="footer-links">

                <li><span><i className="fa-solid fa-hot-tub-person" style={{ color: 'var(--accent-gold)', marginRight: '6px' }}></i> 4-Person Heated Spa</span></li>
                <li><span><i className="fa-solid fa-fire" style={{ color: 'var(--accent-gold)', marginRight: '6px' }}></i> River Stone Fireplace</span></li>
                <li><span><i className="fa-solid fa-wifi" style={{ color: 'var(--accent-gold)', marginRight: '6px' }}></i> High Speed Internet</span></li>
              </ul>
            </div>
            
            <div className="footer-col">
              <h4>Location & Contact</h4>

              <p style={{ marginBottom: '1rem' }}>
                <i className="fa-solid fa-envelope" style={{ color: 'var(--accent-gold)', marginRight: '8px' }}></i>
                tscottage370@gmail.com
              </p>
              <p>
                <i className="fa-solid fa-phone" style={{ color: 'var(--accent-gold)', marginRight: '8px' }}></i>
                +1 (570) 243-1521
              </p>
            </div>
          </div>
          
          <div className="footer-bottom">
            <p>&copy; 2026 T's Cottage Rental Services. All rights reserved.</p>
            <p style={{ fontSize: '0.8rem', color: 'var(--text-muted)' }}>
              Designed for luxury. Powered by React & TypeScript in the Sandbox.
            </p>
          </div>
        </div>
      </footer>
    </div>
  );
}

// ==========================================
// 1. HOME PAGE VIEW COMPONENT
// ==========================================
function HomePage({ 
  property, 
  blockedRanges, 
  onBookNowClick,
  bookings,
  setBookings
}: { 
  property: PropertyDetails; 
  blockedRanges: BlockedRange[]; 
  onBookNowClick: () => void;
  bookings: Booking[];
  setBookings: (b: Booking[]) => void;
}) {
  const [activeProperty, setActiveProperty] = useState<'hickory' | 'moseywood'>('hickory');

  return (
    <div>
      {/* Premium Hero Banner */}
      <section className="hero-sec" style={{ backgroundImage: 'url("./assets/images/01-HomeView_Media-45_Hickory_Rd.jpg")' }}>
        <div className="container">
          <div className="hero-content">
            <span className="hero-subtitle">Boutique Short-Term Rental</span>
            <h1 className="hero-title">Experience Lakeside Luxury in <span className="gold-text">T's Cottage</span></h1>
            <p className="hero-desc">
              Unwind inside a hand-crafted timber frame cabin complete with river stone fireplace warmth, deep lakeside hot tub hydrotherapy, and modern, high-speed amenities.
            </p>
            
            <div style={{ display: 'flex', gap: '1rem', flexWrap: 'wrap' }}>
              <button 
                className="btn-premium"
                onClick={() => {
                  window.location.href = "https://lakeharmonyrental.guestybookings.com/";
                }}
              >
                Book Your Escape <i className="fa-solid fa-arrow-right"></i>
              </button>
              <button 
                className="btn-secondary"
                onClick={() => {
                  const el = document.getElementById('explore-properties-section');
                  if (el) el.scrollIntoView({ behavior: 'smooth' });
                }}
              >
                Explore Properties <i className="fa-regular fa-images"></i>
              </button>
            </div>
          </div>
        </div>
      </section>

      {/* Verified Guest Reviews Sourced from Airbnb */}
      <GuestReviews />

      {/* Explore Properties Master Section */}
      <section id="explore-properties-section" style={{ background: '#171514' }}>
        <div className="container">
          <div className="section-header">
            <h2>Explore Properties</h2>
            <p>Select a property to explore its full high-resolution portfolio, room profiles, and active galleries.</p>
            
            {/* Premium Interactive Switcher */}
            <div className="property-switcher" style={{ display: 'flex', justifyContent: 'center', gap: '1.5rem', marginTop: '2.5rem', flexWrap: 'wrap' }}>
              <button 
                className={`gallery-tab-btn ${activeProperty === 'hickory' ? 'active' : ''}`}
                onClick={() => setActiveProperty('hickory')}
                style={{ minWidth: '220px' }}
              >
                Hickory Property
              </button>
              <button 
                className={`gallery-tab-btn ${activeProperty === 'moseywood' ? 'active' : ''}`}
                onClick={() => setActiveProperty('moseywood')}
                style={{ minWidth: '220px' }}
              >
                Moseywood Property
              </button>
            </div>
          </div>
          
          {/* Revolving Property Pictures (Carousel) */}
          <div style={{ marginBottom: '5rem' }}>
            <div className="section-header" style={{ marginBottom: '2.5rem' }}>
              {activeProperty === 'hickory' ? (
                <div style={{ textAlign: 'left', maxWidth: '800px', margin: '1.5rem auto 0 auto', color: 'var(--text-secondary)', fontSize: '0.975rem', lineHeight: '1.75' }}>
                  <p style={{ marginBottom: '1.25rem' }}>Hickory Chalet in Lake Harmony is a 5 bed 3 bath cottage which can accommodate up to 12 overnight guests. This home is a 10-minute walk to the lake and 7 min drive to the Lake Harmony downtown area.</p>
                  <p style={{ marginBottom: '1.25rem' }}>Boulder and Jack Frost ski mountains are about 10 mins drive from the property.</p>
                  <p style={{ marginBottom: '1.25rem' }}>After a day spent hiking, biking, skiing, kayaking/water sports or shopping at Pocono Premium Outlets (about 25 mins drive away), relax in the spa-like indoor hot tub, which is open year-round, or relax on the deck overlooking the peaceful backyard. Prepare meals in the well-equipped kitchen with a stove, barbecue on the grill, shoot pool in the recreation area, or head outside and gather around the fire pit.</p>
                  <p>There is plenty of space, and plenty to do indoors and outdoors, when your family and friends spend quality time together at T’s Cottage!</p>
                </div>
              ) : (
                <div style={{ textAlign: 'left', maxWidth: '800px', margin: '1.5rem auto 0 auto', color: 'var(--text-secondary)', fontSize: '0.975rem', lineHeight: '1.75' }}>
                  <p style={{ marginBottom: '1.25rem' }}>Moseywood Chalet in Lake Harmony is a 4 bed 2 bath cottage which can accommodate up to 12 overnight guests. This home is a 10-minute walk to the lake and 7 min drive to the Lake Harmony downtown area.</p>
                  <p style={{ marginBottom: '1.25rem' }}>Boulder and Jack Frost ski mountains are about 10 mins drive from the property.</p>
                  <p style={{ marginBottom: '1.25rem' }}>After a day spent hiking, biking, skiing, kayaking/water sports or shopping at Pocono Premium Outlets (about 25 mins drive away), relax in the spa-like indoor hot tub, which is open year-round, or relax on the deck overlooking the peaceful backyard. Prepare meals in the well-equipped kitchen with a stove, barbecue on the grill (coal and Pellet grills), shoot pool in the recreation area, or head outside and gather around the fire pit.</p>
                  <p>There is plenty of space, and plenty to do indoors and outdoors, when your family and friends spend quality time together at T’s Cottage!</p>
                </div>
              )}
            </div>
            <PropertyCarousel activeProperty={activeProperty} />
          </div>

          {/* Interactive Room Explorer */}
          <div style={{ marginBottom: '5rem' }}>
            <div className="section-header" style={{ marginBottom: '2.5rem' }}>
              <h3>Interactive Room Explorer</h3>
              <p>Click through different spaces of the property to view custom interior reports and high-resolution snaps.</p>
            </div>
            <RoomExplorer activeProperty={activeProperty} />
          </div>

          {/* Complete Photo Portfolio */}
          <div>
            <div className="section-header" style={{ marginBottom: '2.5rem' }}>
              <h3>Complete Photo Portfolio</h3>
              <p>Browse the high-resolution captures of the luxury timber frame cottage, interior details, and amenities.</p>
            </div>
            <FullEstateGallery activeProperty={activeProperty} />
          </div>
        </div>
      </section>

      {/* Short Term Rental Services & Grid */}
      <section id="rental-services" style={{ background: '#161514' }}>
        <div className="container">
          <div className="section-header">
            <h2>Premium Rental Amenities & Services</h2>
            <p>We provide curated resort-grade services so you can balance wilderness immersion with luxurious comfort.</p>
          </div>
          
          <div className="amenities-grid">
            <div className="amenity-card glass-panel">
              <div className="amenity-icon-wrapper">
                <i className="fa-solid fa-hot-tub-person"></i>
              </div>
              <h3>Heated Hydro Spa</h3>
              <p>Indulge in a premium integrated 4-person cedar hot tub overlooking the waters, maintained at an optimal 104°F with fully custom therapeutic hydromassage jet nozzles.</p>
            </div>
            
            <div className="amenity-card glass-panel">
              <div className="amenity-icon-wrapper">
                <i className="fa-solid fa-fire"></i>
              </div>
              <h3>River Stone Hearth</h3>
              <p>Cozy up near a massive floor-to-ceiling timber framed stone fireplace. Pre-stocked with seasoned split birch firewood and natural organic pinecone fire starters.</p>
            </div>
            
            <div className="amenity-card glass-panel">
              <div className="amenity-icon-wrapper">
                <i className="fa-solid fa-wifi"></i>
              </div>
              <h3>High Speed Internet</h3>
              <p>High-speed low-latency satellite internet (up to 220 Mbps download). Ideal for remote working cabin days, heavy video calling, or 4K evening movie streaming.</p>
            </div>
            
            <div className="amenity-card glass-panel">
              <div className="amenity-icon-wrapper">
                <i className="fa-solid fa-kitchen-set"></i>
              </div>
              <h3>Professional Kitchen</h3>
              <p>Fully stocked chef's kitchen featuring professional gas burners, double copper sinks, quartz countertops, locally roasted ground coffee, and absolute cooking essentials.</p>
            </div>
          </div>
        </div>
      </section>

    </div>
  );
}

// --- PROPERTIES MULTI-MEDIA REPOSITORIES ---
const PROPERTIES_CAROUSEL_DATA = {
  hickory: [
    {
      img: "./assets/images/01-HomeView_Media-45_Hickory_Rd.jpg",
      title: "The Ultimate Lakeside Sanctuary",
      desc: "Premium natural timber cabin architecture merging beautifully with modern glass windows, shining in the warm ambient lights of dusk."
    },
    {
      img: "./assets/images/04-HomeView_Media-45_Hickory_Rd.jpg",
      title: "Rustic Luxury Living Room",
      desc: "Exposed vaulted cedar ceiling beams, a majestic natural stone fireplace, and premium seating looking out to serene waters."
    },
    {
      img: "./assets/images/11-HomeView_Media-45_Hickory_Rd.jpg",
      title: "Master Loft Suite",
      desc: "Wake up to breathtaking views of misty green forests from a comfortable king bed dressed in rich plush organic linens."
    },
    {
      img: "./assets/images/22-HomeView_Media-45_Hickory_Rd.jpg",
      title: "Private Lakeside Deck & Spa",
      desc: "Submerge in a steaming outdoor wood-integrated hot tub under strings of Edison lights as the sunset paints the sky."
    }
  ],
  moseywood: [
    {
      img: "./assets/images/01-HomeView_Media-370_Moseywood_Rd.-1.jpg",
      title: "Moseywood Chalet Aerial",
      desc: "An incredible high-resolution birds-eye perspective of our boutique lakeside chalet surrounded by thick pine forest canopy."
    },
    {
      img: "./assets/images/04-HomeView_Media-370_Moseywood_Rd.-4.jpg",
      title: "Vaulted Great Room",
      desc: "Soaring wood-plank ceilings, tall glass viewing walls, and custom furniture framing the rustic fireside lounge."
    },
    {
      img: "./assets/images/11-HomeView_Media-370_Moseywood_Rd.-11.jpg",
      title: "Loft Master Suite",
      desc: "Immerse yourself in luxurious comfort under custom exposed log rafters, with panoramic woodland forest canopy views."
    },
    {
      img: "./assets/images/22-HomeView_Media-370_Moseywood_Rd.-22.jpg",
      title: "Lakeside Cedar Spa",
      desc: "Unwind on the private cedar decking inside a pristine, wood-integrated 4-person heated outdoor hot tub under warm Edison lights."
    }
  ]
};

const PROPERTIES_EXPLORER_DATA = {
  hickory: [
    {
      id: "exterior",
      name: "Exterior View",
      img: "./assets/images/02-HomeView_Media-45_Hickory_Rd.jpg",
      title: "Mastercrafted Timber Architecture",
      desc: "Constructed with Canadian red cedar logs and steel glass framing, T's Cottage stands elegantly by the shore. Features a private floating dock, matching kayak slip, and a large wrap-around deck. Perfect for morning coffees and late-night stargazing over the pristine waters."
    },
    {
      id: "living",
      name: "Living Space",
      img: "./assets/images/06-HomeView_Media-45_Hickory_Rd.jpg",
      title: "Warm hearth, High ceilings",
      desc: "Our high-vaulted living area centers around a hand-laid river rock wood fireplace. Large custom floor-to-ceiling windows wash the space in natural daylight. Complete with premium modern sofas, a Sonos surround system, and a warm selection of classic books and board games."
    },
    {
      id: "bedroom",
      name: "Loft Bedroom",
      img: "./assets/images/12-HomeView_Media-45_Hickory_Rd.jpg",
      title: "Tranquility in the Canopy",
      desc: "Situated in the private top-floor loft, the master bedroom boasts a plush king-size hybrid mattress, luxury organic waffle-knit blankets, copper reading lights, and an oversized triangular picture window overlooking the pine forest canopy. Sleep peacefully in nature's absolute silence."
    },
    {
      id: "deck",
      name: "Spa Deck",
      img: "./assets/images/24-HomeView_Media-45_Hickory_Rd.jpg",
      title: "Outdoor Sunset Hydrotherapy",
      desc: "Step out onto the low-profile lakeside cedar deck to discover our custom-integrated 4-person hot tub. Kept at a soothing 104°F, it features variable hydro jets and ambient LED lights. Sit back, relax, and let the gentle sounds of the forest wash your stress away."
    }
  ],
  moseywood: [
    {
      id: "exterior",
      name: "Exterior View",
      img: "./assets/images/02-HomeView_Media-370_Moseywood_Rd.-2.jpg",
      title: "Lakeside Log Architecture",
      desc: "Elegantly constructed with premium natural cedar logs and custom glass framing. Features clean lakefront shoreline views, private deck spaces, and private walking trails through the pristine woods."
    },
    {
      id: "living",
      name: "Living Space",
      img: "./assets/images/05-HomeView_Media-370_Moseywood_Rd.-5.jpg",
      title: "Moss-Accent Hearth Room",
      desc: "Centering around a massive stone-crafted wood fireplace. High-vaulted ceilings and custom glass facades wash the space in warm natural light, accompanied by hand-picked rustic decor and cozy seating."
    },
    {
      id: "bedroom",
      name: "Loft Bedroom",
      img: "./assets/images/11-HomeView_Media-370_Moseywood_Rd.-11.jpg",
      title: "Mist View Canopy Suite",
      desc: "A stunning loft bedroom boasting a premium king hybrid mattress dressed in custom organic linen, with architectural glass framing views of the misty pine forests."
    },
    {
      id: "deck",
      name: "Spa Deck",
      img: "./assets/images/22-HomeView_Media-370_Moseywood_Rd.-22.jpg",
      title: "Outdoor Forest Hydrotherapy",
      desc: "Step onto the low-profile cedar wood spa deck to find a luxury heated hot tub. Designed to maintain a perfect 104°F with custom-adjusted massage jets for ultimate physical recovery."
    }
  ]
};

// --- PROPERTY REVOLVING PICTURES CAROUSEL ---
function PropertyCarousel({ activeProperty }: { activeProperty: 'hickory' | 'moseywood' }) {
  const slides = PROPERTIES_CAROUSEL_DATA[activeProperty];
  
  if (!slides || slides.length === 0) {
    return (
      <div className="carousel-container glass-panel" style={{ height: '350px', display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', textAlign: 'center', padding: '3rem', background: '#1c1a18' }}>
        <i className="fa-regular fa-images" style={{ fontSize: '3rem', color: 'var(--accent-gold)', marginBottom: '1.5rem' }}></i>
        <h3 style={{ fontSize: '1.5rem', marginBottom: '0.5rem', fontFamily: 'var(--font-display)' }}>Property Gallery Coming Soon</h3>
        <p style={{ color: 'var(--text-secondary)', maxWidth: '450px', fontSize: '0.95rem' }}>We are currently capturing premium, high-resolution vistas of our Moseywood Property. Stay tuned!</p>
      </div>
    );
  }

  const [activeIdx, setActiveIdx] = useState(0);
  const autoplayRef = useRef<number | null>(null);

  const startAutoplay = () => {
    stopAutoplay();
    autoplayRef.current = window.setInterval(() => {
      setActiveIdx(prev => (prev + 1) % slides.length);
    }, 5000);
  };

  const stopAutoplay = () => {
    if (autoplayRef.current) {
      clearInterval(autoplayRef.current);
    }
  };

  useEffect(() => {
    setActiveIdx(0);
    startAutoplay();
    return () => stopAutoplay();
  }, [activeProperty]);

  const handlePrev = () => {
    stopAutoplay();
    setActiveIdx(prev => (prev - 1 + slides.length) % slides.length);
    startAutoplay();
  };

  const handleNext = () => {
    stopAutoplay();
    setActiveIdx(prev => (prev + 1) % slides.length);
    startAutoplay();
  };

  const handleDotClick = (idx: number) => {
    stopAutoplay();
    setActiveIdx(idx);
    startAutoplay();
  };

  return (
    <div className="carousel-container" onMouseEnter={stopAutoplay} onMouseLeave={startAutoplay}>
      {slides.map((slide, idx) => (
        <div className={`carousel-slide ${idx === activeIdx ? 'active' : ''}`} key={idx}>
          <img src={slide.img} alt={slide.title} className="carousel-img" />
          <div className="carousel-overlay">
            <h3 className="carousel-caption-title gold-text">{slide.title}</h3>
            <p className="carousel-caption-desc">{slide.desc}</p>
          </div>
        </div>
      ))}
      
      {/* Controls */}
      <button className="carousel-btn carousel-btn-prev" onClick={handlePrev} aria-label="Previous image">
        <i className="fa-solid fa-chevron-left"></i>
      </button>
      <button className="carousel-btn carousel-btn-next" onClick={handleNext} aria-label="Next image">
        <i className="fa-solid fa-chevron-right"></i>
      </button>
      
      {/* Dots indicator */}
      <div className="carousel-dots">
        {slides.map((_, idx) => (
          <button 
            key={idx} 
            className={`carousel-dot ${idx === activeIdx ? 'active' : ''}`} 
            onClick={() => handleDotClick(idx)}
            aria-label={`Go to slide ${idx + 1}`}
          />
        ))}
      </div>
    </div>
  );
}

// --- INTERACTIVE ROOM EXPLORER ---
function RoomExplorer({ activeProperty }: { activeProperty: 'hickory' | 'moseywood' }) {
  const rooms = PROPERTIES_EXPLORER_DATA[activeProperty];
  
  if (!rooms || rooms.length === 0) {
    return (
      <div className="glass-panel" style={{ padding: '3.5rem 2rem', textAlign: 'center', background: '#1c1a18', borderRadius: 'var(--border-radius-lg)', border: '1px solid var(--glass-border)' }}>
        <i className="fa-solid fa-compass" style={{ fontSize: '2.5rem', color: 'var(--accent-gold)', marginBottom: '1.25rem' }}></i>
        <h4 style={{ fontSize: '1.25rem', marginBottom: '0.5rem', fontFamily: 'var(--font-display)' }}>Room Explorer Under Construction</h4>
        <p style={{ color: 'var(--text-secondary)', fontSize: '0.95rem' }}>Interior walkthrough reports and architecture profiles for Moseywood are being compiled.</p>
      </div>
    );
  }
  const [activeTab, setActiveTab] = useState("exterior");
  const activeRoom = rooms.find(r => r.id === activeTab) || rooms[0];

  useEffect(() => {
    setActiveTab("exterior");
  }, [activeProperty]);

  return (
    <div className="about-explorer-grid">
      <div className="about-text">
        <h3>Our Hosting Philosophy</h3>
        <p>
          T's Cottage was born from a desire to blend rugged lakefront scenery with a premium architectural design language. Each section of our wood cabin has been refined to emphasize rustic cedar trunks while providing modern thermal seals and luxury finishes.
        </p>
        <p>
          We operate as a high-end short-term lodging service, providing seamless check-in processes, custom local guide handbooks, and rapid-response staff support. Use our explorer widget to explore specific property corners in close-up details.
        </p>
      </div>
      
      <div className="explorer-widget">
        <div className="explorer-tabs">
          {rooms.map(tab => (
            <button
              key={tab.id}
              className={`explorer-tab ${tab.id === activeTab ? 'active' : ''}`}
              onClick={() => setActiveTab(tab.id)}
            >
              {tab.name}
            </button>
          ))}
        </div>
        
        <div className="explorer-display glass-panel">
          <img src={activeRoom.img} alt={activeRoom.title} className="explorer-display-img" />
          <div className="explorer-display-overlay">
            <h4 className="gold-text">{activeRoom.title}</h4>
            <p>{activeRoom.desc}</p>
          </div>
        </div>
      </div>
    </div>
  );
}

// --- FULL ESTABLISHED ESTATE GALLERY DATA ---
const ALL_GALLERY_IMAGES = [
  { url: "./assets/images/01-HomeView_Media-45_Hickory_Rd.jpg", category: "exterior", title: "Cottage Front Aerial", desc: "A sweeping view of the timber frame cottage under the tall pines." },
  { url: "./assets/images/02-HomeView_Media-45_Hickory_Rd.jpg", category: "exterior", title: "Shoreline Perspective", desc: "Stunning lakeside view showing the cottage nestled beautifully on the shoreline." },
  { url: "./assets/images/03-HomeView_Media-45_Hickory_Rd.jpg", category: "exterior", title: "Front Entrance & Porch", desc: "Warm and inviting log-structured entryway welcomes you to the cabin." },
  { url: "./assets/images/04-HomeView_Media-45_Hickory_Rd.jpg", category: "interior", title: "Main Living Great Room", desc: "Soaring cathedral ceilings with massive windows looking out over the water." },
  { url: "./assets/images/05-HomeView_Media-45_Hickory_Rd.jpg", category: "interior", title: "Cozy Fireside Seating", desc: "Plush modern sofas gathered around the hand-laid river rock fireplace." },
  { url: "./assets/images/06-HomeView_Media-45_Hickory_Rd.jpg", category: "interior", title: "Open-Concept Dining & Kitchen", desc: "Elegant chef's kitchen space featuring quartz counters and premium wood cabinetry." },
  { url: "./assets/images/07-HomeView_Media-45_Hickory_Rd.jpg", category: "interior", title: "Gourmet Coffee Bar", desc: "Dedicated espresso and coffee station stocked with premium local blends." },
  { url: "./assets/images/08-HomeView_Media-45_Hickory_Rd.jpg", category: "interior", title: "First-Floor Guest Suite", desc: "Warm tongue-and-groove pine walls wrapping a premium queen-size hybrid bed." },
  { url: "./assets/images/09-HomeView_Media-45_Hickory_Rd.jpg", category: "interior", title: "Rustic Main Level Bathroom", desc: "Modern fixtures, custom copper piping accents, and organic waffle-knit towels." },
  { url: "./assets/images/10-HomeView_Media-45_Hickory_Rd.jpg", category: "interior", title: "Staircase to Loft", desc: "Custom floating cedar stairs showcasing timber joinery and black steel railings." },
  { url: "./assets/images/11-HomeView_Media-45_Hickory_Rd.jpg", category: "interior", title: "Master Bedroom Loft", desc: "King hybrid mattress facing a large window with direct views of the lake canopy." },
  { url: "./assets/images/12-HomeView_Media-45_Hickory_Rd.jpg", category: "interior", title: "Loft Desk Workstation", desc: "Quiet writing desk overlooking the living area with high-speed Starlink Wi-Fi." },
  { url: "./assets/images/13-HomeView_Media-45_Hickory_Rd.jpg", category: "interior", title: "En-Suite Spa Bath", desc: "Indulgent walk-in rain shower featuring natural slate tiles and premium amenities." },
  { url: "./assets/images/14-HomeView_Media-45_Hickory_Rd.jpg", category: "interior", title: "Secondary Loft Guest Room", desc: "Two comfortable twin beds, perfect for family stays or extra guests." },
  { url: "./assets/images/15-HomeView_Media-45_Hickory_Rd.jpg", category: "interior", title: "Cozy Reading Nook", desc: "Tucked-away window seat perfect for enjoying a classic novel or early morning tea." },
  { url: "./assets/images/16-HomeView_Media-45_Hickory_Rd.jpg", category: "exterior", title: "Upper Deck Balcony", desc: "Private master balcony offering an elevated view of the lake's morning mist." },
  { url: "./assets/images/17-HomeView_Media-45_Hickory_Rd.jpg", category: "amenities", title: "Hand-Split Firewood Rack", desc: "Generously stocked seasoned birch log stacks ready for cozy fireplace evenings." },
  { url: "./assets/images/18-HomeView_Media-45_Hickory_Rd.jpg", category: "exterior", title: "Wrap-Around Cedar Deck", desc: "Oversized lakeside deck complete with premium outdoor dining set and BBQ grill." },
  { url: "./assets/images/19-HomeView_Media-45_Hickory_Rd.jpg", category: "exterior", title: "Deck Loungers", desc: "Comfortable sun loungers looking straight out over the tranquil blue waters." },
  { url: "./assets/images/20-HomeView_Media-45_Hickory_Rd.jpg", category: "amenities", title: "Lake-Facing Fire Pit", desc: "Bespoke stone-ringed fire pit surrounded by Adirondack chairs near the water." },
  { url: "./assets/images/21-HomeView_Media-45_Hickory_Rd.jpg", category: "amenities", title: "Private Floating Dock", desc: "Sturdy wood dock extending into deep clear water with swim ladder attached." },
  { url: "./assets/images/22-HomeView_Media-45_Hickory_Rd.jpg", category: "amenities", title: "Heated Hydrotherapy Spa", desc: "Lakeside 6-person hot tub keeping a steady 104°F temperature under Edison lights." },
  { url: "./assets/images/23-HomeView_Media-45_Hickory_Rd.jpg", category: "amenities", title: "Adventure Kayaks", desc: "Two single-passenger kayaks and paddleboard positioned on the launching deck." },
  { url: "./assets/images/24-HomeView_Media-45_Hickory_Rd.jpg", category: "exterior", title: "Cottage Forest Path", desc: "Meandering woodchip pathway leading down through mossy rocks to the shore." },
  { url: "./assets/images/25-HomeView_Media-45_Hickory_Rd.jpg", category: "exterior", title: "Dusk Exterior Illumination", desc: "Cottage window warm lights casting a golden reflection on the dark calm lake." },
  { url: "./assets/images/26-HomeView_Media-45_Hickory_Rd.jpg", category: "exterior", title: "Starry Sky Panorama", desc: "Breathtaking long-exposure view of the Milky Way directly above the cabin roof." }
];

const MOSEYWOOD_GALLERY_IMAGES = Array.from({ length: 57 }, (_, i) => {
  const num = i + 1;
  const padNum = num.toString().padStart(2, '0');
  
  // Categorize based on index
  let category: 'exterior' | 'interior' | 'amenities' = 'exterior';
  if (num >= 4 && num <= 15) {
    category = 'interior';
  } else if (num >= 16 && num <= 23) {
    category = 'amenities';
  } else if (num >= 24 && num <= 45) {
    category = 'interior';
  } else if (num >= 46) {
    category = 'exterior';
  }

  // Generate pleasant titles
  let title = `Moseywood Vista #${num}`;
  if (num === 1) title = "Moseywood Chalet Aerial";
  else if (num === 2) title = "Lakeside Log Architecture";
  else if (num === 3) title = "Forest Approach";
  else if (num === 4) title = "Vaulted Great Room";
  else if (num === 5) title = "Fireside Hearth";
  else if (num === 6) title = "Woodland Kitchen";
  else if (num === 11) title = "Loft Master Suite";
  else if (num === 22) title = "Lakeside Cedar Spa";

  return {
    url: `./assets/images/${padNum}-HomeView_Media-370_Moseywood_Rd.-${num}.jpg`,
    category,
    title,
    desc: `Experience dense woodland luxury at our premium Moseywood property. Capture #${num} showcasing modern timber craft and pristine nature.`
  };
});

const PROPERTIES_GALLERY_DATA = {
  hickory: ALL_GALLERY_IMAGES,
  moseywood: MOSEYWOOD_GALLERY_IMAGES
};

function FullEstateGallery({ activeProperty }: { activeProperty: 'hickory' | 'moseywood' }) {
  const galleryImages = PROPERTIES_GALLERY_DATA[activeProperty];

  if (!galleryImages || galleryImages.length === 0) {
    return (
      <div className="glass-panel" style={{ padding: '4.5rem 2rem', textAlign: 'center', background: '#1c1a18', borderRadius: 'var(--border-radius-lg)', border: '1px solid var(--glass-border)' }}>
        <i className="fa-solid fa-camera-retro" style={{ fontSize: '3rem', color: 'var(--accent-gold)', marginBottom: '1.5rem' }}></i>
        <h3 style={{ fontSize: '1.5rem', marginBottom: '0.5rem', fontFamily: 'var(--font-display)' }}>Photo Portfolio Coming Soon</h3>
        <p style={{ color: 'var(--text-secondary)', maxWidth: '500px', margin: '0 auto', fontSize: '0.95rem' }}>All 57 high-resolution forest captures of T's Moseywood Property are undergoing digital optimization. Check back shortly!</p>
      </div>
    );
  }

  const [filter, setFilter] = useState<'all' | 'exterior' | 'interior' | 'amenities'>('all');
  const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);
  
  const filteredImages = filter === 'all' 
    ? galleryImages 
    : galleryImages.filter(img => img.category === filter);

  useEffect(() => {
    setFilter('all');
    setLightboxIndex(null);
  }, [activeProperty]);

  const handlePrev = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (lightboxIndex !== null) {
      setLightboxIndex(prev => {
        if (prev === null) return 0;
        const currentFilteredIndex = filteredImages.findIndex(img => img.url === galleryImages[prev].url);
        const newFilteredIndex = (currentFilteredIndex - 1 + filteredImages.length) % filteredImages.length;
        return galleryImages.findIndex(img => img.url === filteredImages[newFilteredIndex].url);
      });
    }
  };

  const handleNext = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (lightboxIndex !== null) {
      setLightboxIndex(prev => {
        if (prev === null) return 0;
        const currentFilteredIndex = filteredImages.findIndex(img => img.url === galleryImages[prev].url);
        const newFilteredIndex = (currentFilteredIndex + 1) % filteredImages.length;
        return galleryImages.findIndex(img => img.url === filteredImages[newFilteredIndex].url);
      });
    }
  };

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (lightboxIndex !== null) {
        if (e.key === "ArrowLeft") handlePrev(e as any);
        if (e.key === "ArrowRight") handleNext(e as any);
        if (e.key === "Escape") setLightboxIndex(null);
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [lightboxIndex, filter, activeProperty]);

  return (
    <div className="full-gallery-wrapper">
      {/* Filtering tabs */}
      <div className="gallery-tabs">
        {(['all', 'exterior', 'interior', 'amenities'] as const).map(tab => (
          <button
            key={tab}
            className={`gallery-tab-btn ${filter === tab ? 'active' : ''}`}
            onClick={() => setFilter(tab)}
          >
            {tab.charAt(0).toUpperCase() + tab.slice(1)}
          </button>
        ))}
      </div>
      
      {/* Gallery Grid */}
      <div className="gallery-grid">
        {filteredImages.map((img) => {
          const globalIdx = galleryImages.findIndex(i => i.url === img.url);
          return (
            <div 
              key={img.url} 
              className="gallery-card glass-panel"
              onClick={() => setLightboxIndex(globalIdx)}
            >
              <div className="gallery-img-container">
                <img src={img.url} alt={img.title} className="gallery-thumbnail" loading="lazy" />
                <div className="gallery-hover-overlay">
                  <div className="gallery-hover-info">
                    <span className="gallery-hover-category">{img.category.toUpperCase()}</span>
                    <h4>{img.title}</h4>
                    <p>{img.desc}</p>
                    <div className="gallery-zoom-icon">
                      <i className="fa-solid fa-maximize"></i>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
      
      {/* Lightbox Modal */}
      {lightboxIndex !== null && (
        <div className="lightbox-modal" onClick={() => setLightboxIndex(null)}>
          <button className="lightbox-close" onClick={() => setLightboxIndex(null)}>
            <i className="fa-solid fa-xmark"></i>
          </button>
          
          <button className="lightbox-nav lightbox-prev" onClick={handlePrev}>
            <i className="fa-solid fa-chevron-left"></i>
          </button>
          
          <div className="lightbox-content" onClick={(e) => e.stopPropagation()}>
            <img 
              src={galleryImages[lightboxIndex].url} 
              alt={galleryImages[lightboxIndex].title} 
              className="lightbox-main-img" 
            />
            <div className="lightbox-caption glass-panel">
              <span className="lightbox-category">{galleryImages[lightboxIndex].category.toUpperCase()}</span>
              <h3>{galleryImages[lightboxIndex].title}</h3>
              <p>{galleryImages[lightboxIndex].desc}</p>
              <div className="lightbox-counter">
                {filteredImages.findIndex(img => img.url === galleryImages[lightboxIndex].url) + 1} / {filteredImages.length}
              </div>
            </div>
          </div>
          
          <button className="lightbox-nav lightbox-next" onClick={handleNext}>
            <i className="fa-solid fa-chevron-right"></i>
          </button>
        </div>
      )}
    </div>
  );
}

// --- VERIFIED AIRBNB GUEST TESTIMONIALS ---
function GuestReviews() {
  const [activeFilter, setActiveFilter] = useState<'all' | 'hickory' | 'moseywood'>('all');

  const filteredReviews = activeFilter === 'all'
    ? REVIEWS_DATA
    : REVIEWS_DATA.filter(rev => rev.property === activeFilter);

  return (
    <section className="reviews-section">
      <div className="container">
        <div className="section-header">
          <span className="hero-subtitle" style={{ display: 'block', marginBottom: '0.5rem', textAlign: 'center' }}>Guest Vows & Social Proof</span>
          <h2>Verified Guest Reviews</h2>
          <p>Read real, 5-star experiences from guests who stayed at our luxury Pocono mountain retreats.</p>
          
          {/* Review Summary Score */}
          <div className="reviews-score-badge glass-panel-light">
            <span className="score-number">5.0</span>
            <div className="score-stars">
              <i className="fa-solid fa-star"></i>
              <i className="fa-solid fa-star"></i>
              <i className="fa-solid fa-star"></i>
              <i className="fa-solid fa-star"></i>
              <i className="fa-solid fa-star"></i>
            </div>
            <span className="score-text">Exceptional Rating based on 48+ Airbnb stays</span>
          </div>

          {/* Interactive filter tabs */}
          <div className="reviews-filter-tabs">
            <button 
              className={`reviews-filter-btn ${activeFilter === 'all' ? 'active' : ''}`}
              onClick={() => setActiveFilter('all')}
            >
              All Reviews
            </button>
            <button 
              className={`reviews-filter-btn ${activeFilter === 'hickory' ? 'active' : ''}`}
              onClick={() => setActiveFilter('hickory')}
            >
              Hickory Chalet
            </button>
            <button 
              className={`reviews-filter-btn ${activeFilter === 'moseywood' ? 'active' : ''}`}
              onClick={() => setActiveFilter('moseywood')}
            >
              Moseywood Chalet
            </button>
          </div>
        </div>

        {/* Review Cards Grid */}
        <div className="reviews-grid">
          {filteredReviews.map((rev) => (
            <div className="review-card glass-panel" key={rev.id}>
              <div className="review-card-header">
                <div className="review-avatar">
                  {rev.avatarText}
                </div>
                <div className="review-meta">
                  <h4>{rev.guestName}</h4>
                  <span className="review-stay-date">{rev.stayDate}</span>
                </div>
                <div className="review-source" title="Verified Airbnb Stay">
                  <i className="fa-brands fa-airbnb airbnb-icon"></i>
                </div>
              </div>

              <div className="review-stars-row">
                {Array.from({ length: rev.rating }).map((_, i) => (
                  <i className="fa-solid fa-star" key={i}></i>
                ))}
              </div>

              <p className="review-body-text">
                "{rev.reviewText}"
              </p>

              <div className="review-card-footer">
                <span className="verified-badge">
                  <i className="fa-solid fa-circle-check"></i> Verified Stay
                </span>
                <span className="airbnb-tag">via Airbnb</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// --- INTERACTIVE PRICE CALCULATOR ---
function PriceCalculator({ 
  property, 
  blockedRanges,
  bookings,
  setBookings
}: { 
  property: PropertyDetails; 
  blockedRanges: BlockedRange[];
  bookings: Booking[];
  setBookings: (b: Booking[]) => void;
}) {
  const [checkIn, setCheckIn] = useState("2026-06-12");
  const [checkOut, setCheckOut] = useState("2026-06-16");
  const [guests, setGuests] = useState(2);
  const [guestName, setGuestName] = useState("");
  const [guestEmail, setGuestEmail] = useState("");
  const [isBooked, setIsBooked] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");

  // Calculation helpers
  const getDaysCount = () => {
    if (!checkIn || !checkOut) return 0;
    const start = new Date(checkIn + "T00:00:00");
    const end = new Date(checkOut + "T00:00:00");
    const diffTime = end.getTime() - start.getTime();
    if (diffTime <= 0) return 0;
    return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  };

  const nights = getDaysCount();
  const accommodationTotal = nights * property.baseRate;
  const tax = (accommodationTotal + property.cleaningFee) * property.taxRate;
  const finalTotal = accommodationTotal > 0 ? (accommodationTotal + property.cleaningFee + tax) : 0;

  // Validate dates overlap against active blocked ranges
  const checkOverlap = (startStr: string, endStr: string) => {
    const checkInDate = new Date(startStr + "T00:00:00");
    const checkOutDate = new Date(endStr + "T23:59:59");
    
    if (checkInDate.getTime() < new Date().setHours(0,0,0,0)) {
      return "Selected dates cannot be in the past.";
    }
    if (checkInDate.getTime() >= checkOutDate.getTime()) {
      return "Check-out date must be after check-in date.";
    }
    
    // Scan all blocked date intervals
    for (const range of blockedRanges) {
      if (
        (checkInDate >= range.start && checkInDate < range.end) || // Start falls inside
        (checkOutDate > range.start && checkOutDate <= range.end) || // End falls inside
        (checkInDate <= range.start && checkOutDate >= range.end)    // Selection envelops blocked
      ) {
        return `Selected dates overlap with an existing booking synchronized via: ${range.source}. Please check availability calendar.`;
      }
    }
    return "";
  };

  const handleBookingSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMessage("");
    
    if (!guestName || !guestEmail || !checkIn || !checkOut) {
      setErrorMessage("Please complete all personal and stay details.");
      return;
    }

    const overlapError = checkOverlap(checkIn, checkOut);
    if (overlapError) {
      setErrorMessage(overlapError);
      return;
    }

    // Process secure new request
    const newRequest: Booking = {
      id: `B-${Math.floor(1000 + Math.random() * 9000)}`,
      guestName,
      guestEmail,
      checkIn,
      checkOut,
      guestsCount: guests,
      totalPrice: parseFloat(finalTotal.toFixed(2)),
      status: "Pending",
      createdDate: new Date().toISOString().split('T')[0]
    };

    setBookings([newRequest, ...bookings]);
    setIsBooked(true);

    // Clean inputs
    setGuestName("");
    setGuestEmail("");
  };

  return (
    <div className="booking-section-wrapper">
      <div className="about-text">
        <h3>Lakeside Stay Quotes</h3>
        <p>
          We pride ourselves on offering clear, transparent pricing. Enter your dates and guest numbers in the Quote Builder. Our server will calculate seasonal rental rates, standard tax, and cleaning fees instantly.
        </p>
        <div style={{ marginTop: '2rem' }}>
          <h4><i className="fa-solid fa-shield-halved" style={{ color: 'var(--accent-gold)', marginRight: '8px' }}></i> Booking Protection Guarantee</h4>
          <p style={{ fontSize: '0.95rem', color: 'var(--text-secondary)' }}>
            All booking requests undergo active calendar conflict checks. Once submitted, your dates are temporarily soft-blocked until our property host approves the reservation (typically under 2 hours).
          </p>
        </div>
      </div>
      
      <div className="calc-glass-box glass-panel">
        <h4 style={{ marginBottom: '1.5rem', fontFamily: 'var(--font-display)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
          Quote Builder
        </h4>
        
        {isBooked ? (
          <div className="booking-confirm-banner">
            <i className="fa-solid fa-circle-check"></i>
            <strong>Booking Request Received!</strong>
            <p style={{ fontSize: '0.85rem', marginTop: '0.5rem', color: 'var(--text-secondary)' }}>
              Thank you for reserving T's Cottage. A staff concierge will review your stay request (B-XXXX) shortly. We have soft-blocked your selected dates temporarily!
            </p>
            <button 
              className="btn-premium" 
              style={{ marginTop: '1rem', width: '100%', justifyContent: 'center' }}
              onClick={() => setIsBooked(false)}
            >
              Build Another Quote
            </button>
          </div>
        ) : (
          <form onSubmit={handleBookingSubmit}>
            <div className="calc-grid">
              <div className="search-field">
                <label htmlFor="calc-in">Check-in Date</label>
                <input 
                  type="date" 
                  id="calc-in" 
                  value={checkIn}
                  onChange={(e) => {
                    setCheckIn(e.target.value);
                    setErrorMessage("");
                  }}
                  required
                />
              </div>
              <div className="search-field">
                <label htmlFor="calc-out">Check-out Date</label>
                <input 
                  type="date" 
                  id="calc-out" 
                  value={checkOut}
                  onChange={(e) => {
                    setCheckOut(e.target.value);
                    setErrorMessage("");
                  }}
                  required
                />
              </div>
            </div>
            
            <div className="calc-grid" style={{ marginBottom: '1.5rem' }}>
              <div className="search-field">
                <label htmlFor="calc-guests">Total Guests</label>
                <select 
                  id="calc-guests" 
                  value={guests}
                  onChange={(e) => setGuests(parseInt(e.target.value))}
                >
                  <option value={1}>1 Guest</option>
                  <option value={2}>2 Guests</option>
                  <option value={3}>3 Guests</option>
                  <option value={4}>4 Guests</option>
                  <option value={5}>5 Guests (Cozy)</option>
                  <option value={6}>6 Guests (Max Capacity)</option>
                </select>
              </div>
              
              <div className="search-field" style={{ justifyContent: 'end' }}>
                <span style={{ fontSize: '0.85rem', color: 'var(--text-secondary)', marginBottom: '0.25rem' }}>Base Pricing Rate:</span>
                <strong style={{ fontSize: '1.1rem', color: 'var(--accent-gold)' }}>${property.baseRate} / night</strong>
              </div>
            </div>
            
            <div className="calc-grid">
              <div className="search-field" style={{ gridColumn: 'span 2' }}>
                <label htmlFor="calc-name">Full Guest Name</label>
                <input 
                  type="text" 
                  id="calc-name" 
                  placeholder="e.g. Sarah Jenkins"
                  value={guestName}
                  onChange={(e) => setGuestName(e.target.value)}
                  required
                />
              </div>
            </div>
            
            <div className="calc-grid" style={{ marginTop: '1rem', marginBottom: '1.5rem' }}>
              <div className="search-field" style={{ gridColumn: 'span 2' }}>
                <label htmlFor="calc-email">Email Address</label>
                <input 
                  type="email" 
                  id="calc-email" 
                  placeholder="e.g. sarah.j@gmail.com"
                  value={guestEmail}
                  onChange={(e) => setGuestEmail(e.target.value)}
                  required
                />
              </div>
            </div>
            
            {/* Calculation summary */}
            <div className="calc-details">
              <div className="calc-row">
                <span>Accommodation ({nights} night{nights !== 1 ? 's' : ''} at ${property.baseRate}/nt)</span>
                <span>${accommodationTotal}</span>
              </div>
              <div className="calc-row">
                <span>Standard Cleaning & Linen Fee</span>
                <span>${property.cleaningFee}</span>
              </div>
              <div className="calc-row">
                <span>State Occupancy Tax ({(property.taxRate * 100).toFixed(0)}%)</span>
                <span>${tax.toFixed(2)}</span>
              </div>
              
              <div className="calc-row total">
                <span>Estimated Stay Total</span>
                <span>${finalTotal.toFixed(2)}</span>
              </div>
            </div>

            {errorMessage && (
              <div style={{ color: '#d17575', fontSize: '0.85rem', marginBottom: '1rem', padding: '0.75rem', background: 'rgba(197, 87, 87, 0.1)', border: '1px solid rgba(197, 87, 87, 0.25)', borderRadius: '4px' }}>
                <i className="fa-solid fa-circle-exclamation" style={{ marginRight: '6px' }}></i> {errorMessage}
              </div>
            )}
            
            <button 
              type="submit" 
              className="btn-premium" 
              style={{ width: '100%', justifyContent: 'center' }}
              disabled={nights <= 0}
            >
              Request Staying Dates <i className="fa-solid fa-calendar-check"></i>
            </button>
          </form>
        )}
      </div>
    </div>
  );
}



// ==========================================
// 3. TERMS & CONDITIONS PAGE VIEW
// ==========================================
function TermsPage() {
  const [activeAccordion, setActiveAccordion] = useState<number | null>(0);

  const toggleAccordion = (idx: number) => {
    if (activeAccordion === idx) {
      setActiveAccordion(null);
    } else {
      setActiveAccordion(idx);
    }
  };

  return (
    <section style={{ paddingTop: '140px' }}>
      <div className="container">
        <div className="section-header">
          <h2>Terms & Conditions</h2>
          <p>Please review our rental agreements, safety directives, and stay policies prior to booking T's Cottage.</p>
        </div>
        
        <div className="terms-wrapper">
          {TERMS_DATA.map((term, idx) => (
            <div 
              className={`accordion-item glass-panel ${activeAccordion === idx ? 'active' : ''}`} 
              key={idx}
            >
              <button className="accordion-trigger" onClick={() => toggleAccordion(idx)}>
                <span>{term.title}</span>
                <i className="fa-solid fa-chevron-down"></i>
              </button>
              <div className="accordion-panel">
                <div className="accordion-content">
                  {term.content.split('\n').map((para, pidx) => {
                    if (para.startsWith('-')) {
                      return <li key={pidx} style={{ marginLeft: '1rem', marginBottom: '0.5rem' }}>{para.substring(1).trim()}</li>;
                    }
                    return <p key={pidx} style={{ marginBottom: '1rem' }}>{para}</p>;
                  })}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ==========================================
// 4. STAFF ADMIN PORTAL VIEW COMPONENT
// ==========================================
function AdminPortalPage({
  property,
  setProperty,
  bookings,
  setBookings,
  channels,
  setChannels,
  blockedRanges,
  setBlockedRanges
}: {
  property: PropertyDetails;
  setProperty: (p: PropertyDetails) => void;
  bookings: Booking[];
  setBookings: (b: Booking[]) => void;
  channels: SyncChannel[];
  setChannels: (c: SyncChannel[]) => void;
  blockedRanges: BlockedRange[];
  setBlockedRanges: (b: BlockedRange[]) => void;
}) {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [password, setPassword] = useState("");
  const [loginError, setLoginError] = useState("");
  const [adminTab, setAdminTab] = useState<'overview' | 'bookings' | 'channels' | 'settings'>('overview');

  // Sync Input States
  const [newChannelName, setNewChannelName] = useState("");
  const [newChannelUrl, setNewChannelUrl] = useState("");
  const [channelMessage, setChannelMessage] = useState("");

  // Edit Settings states (initialized from parent state)
  const [tempTitle, setTempTitle] = useState(property.title);
  const [tempRate, setTempRate] = useState(property.baseRate);
  const [tempCleaning, setTempCleaning] = useState(property.cleaningFee);
  const [tempDesc, setTempDesc] = useState(property.description);
  const [settingsMessage, setSettingsMessage] = useState("");

  const handleLogin = (e: React.FormEvent) => {
    e.preventDefault();
    setLoginError("");
    
    // Premium Staff login bypass (Password matches approved spec)
    if (password === "tscottage2026") {
      setIsLoggedIn(true);
      setLoginError("");
    } else {
      setLoginError("Invalid concierge staff credential. Please check credentials.");
    }
  };

  const handleLogout = () => {
    setIsLoggedIn(false);
    setPassword("");
  };

  // Booking Actions
  const updateBookingStatus = (id: string, newStatus: 'Approved' | 'Denied') => {
    const updated = bookings.map(b => {
      if (b.id === id) {
        return { ...b, status: newStatus };
      }
      return b;
    });
    setBookings(updated);
  };

  const deleteBooking = (id: string) => {
    const filtered = bookings.filter(b => b.id !== id);
    setBookings(filtered);
  };

  // Calendar Synced Channel actions
  const handleAddChannel = (e: React.FormEvent) => {
    e.preventDefault();
    setChannelMessage("");
    
    if (!newChannelName || !newChannelUrl) {
      setChannelMessage("Please complete sync channel fields.");
      return;
    }

    const newChan: SyncChannel = {
      id: `sync-${Math.floor(1000 + Math.random() * 9000)}`,
      name: newChannelName,
      url: newChannelUrl,
      lastSynced: "Never Synced",
      status: "Success"
    };

    setChannels([...channels, newChan]);
    setNewChannelName("");
    setNewChannelUrl("");
    setChannelMessage("External channel channel sync registered successfully!");
  };

  const deleteChannel = (id: string) => {
    const filtered = channels.filter(c => c.id !== id);
    setChannels(filtered);
  };

  // Update Settings handler
  const handleSaveSettings = (e: React.FormEvent) => {
    e.preventDefault();
    setSettingsMessage("");
    
    const updated: PropertyDetails = {
      ...property,
      title: tempTitle,
      baseRate: tempRate,
      cleaningFee: tempCleaning,
      description: tempDesc
    };

    setProperty(updated);
    setSettingsMessage("Listing attributes saved and pushed successfully!");
  };

  // Summary Metrics helpers
  const totalRevenue = bookings
    .filter(b => b.status === "Approved")
    .reduce((acc, curr) => acc + curr.totalPrice, 0);

  const approvedBookingsCount = bookings.filter(b => b.status === "Approved").length;
  const pendingBookingsCount = bookings.filter(b => b.status === "Pending").length;

  if (!isLoggedIn) {
    return (
      <section className="admin-view">
        <div className="container">
          <div className="admin-login-card glass-panel">
            <i className="fa-solid fa-lock"></i>
            <h2 style={{ fontSize: '1.8rem', marginBottom: '0.5rem', fontFamily: 'var(--font-display)' }}>Staff Login</h2>
            <p style={{ color: 'var(--text-secondary)', fontSize: '0.9rem', marginBottom: '2rem' }}>
              Access our rental back-office dashboard.
            </p>
            
            <form onSubmit={handleLogin}>
              <div className="form-group">
                <label htmlFor="admin-pass">Security Code</label>
                <input 
                  type="password" 
                  id="admin-pass" 
                  placeholder="Enter staff security password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                />
              </div>
              
              {loginError && (
                <div style={{ color: '#d17575', fontSize: '0.85rem', marginBottom: '1.25rem', textAlign: 'left' }}>
                  <i className="fa-solid fa-triangle-exclamation"></i> {loginError}
                </div>
              )}
              
              <button type="submit" className="btn-premium" style={{ width: '100%', justifyContent: 'center' }}>
                Verify Credentials <i className="fa-solid fa-unlock-keyhole"></i>
              </button>
            </form>
            <div style={{ marginTop: '1.5rem', fontSize: '0.75rem', color: 'var(--text-muted)' }}>
              Developer Bypass Credential: <code style={{ color: 'var(--accent-gold)' }}>tscottage2026</code>
            </div>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="admin-view">
      <div className="container">
        <div className="admin-dashboard-layout">
          
          {/* Dashboard Left Sidebar */}
          <aside className="admin-sidebar glass-panel">
            <h3 style={{ fontSize: '0.9rem', color: 'var(--accent-gold)', marginBottom: '1.25rem', textTransform: 'uppercase', letterSpacing: '0.08em', padding: '0 0.5rem' }}>
              Staff Controls
            </h3>
            
            <button 
              className={`admin-sidebar-btn ${adminTab === 'overview' ? 'active' : ''}`}
              onClick={() => setAdminTab('overview')}
            >
              <i className="fa-solid fa-chart-line"></i> Overview
            </button>
            
            <button 
              className={`admin-sidebar-btn ${adminTab === 'bookings' ? 'active' : ''}`}
              onClick={() => setAdminTab('bookings')}
            >
              <i className="fa-solid fa-calendar-days"></i> Booking Requests ({pendingBookingsCount})
            </button>
            
            <button 
              className={`admin-sidebar-btn ${adminTab === 'channels' ? 'active' : ''}`}
              onClick={() => setAdminTab('channels')}
            >
              <i className="fa-solid fa-arrows-rotate"></i> Sync Feeds
            </button>
            
            <button 
              className={`admin-sidebar-btn ${adminTab === 'settings' ? 'active' : ''}`}
              onClick={() => setAdminTab('settings')}
            >
              <i className="fa-solid fa-sliders"></i> Property Settings
            </button>
            
            <div className="admin-sidebar-footer">
              <button className="btn-secondary" style={{ width: '100%', justifyContent: 'center', fontSize: '0.8rem', padding: '0.6rem' }} onClick={handleLogout}>
                Logout Portal <i className="fa-solid fa-right-from-bracket"></i>
              </button>
            </div>
          </aside>
          
          {/* Dashboard Main Panel */}
          <div className="admin-panel-card glass-panel">
            
            {/* TAB 1: OVERVIEW METRICS */}
            {adminTab === 'overview' && (
              <div>
                <div className="admin-panel-header">
                  <h2 className="admin-panel-title">Back-Office Summary</h2>
                  <span style={{ fontSize: '0.9rem', color: 'var(--text-secondary)' }}>Welcome, Administrator</span>
                </div>
                
                <div className="admin-stats-grid">
                  <div className="stat-card glass-panel-light">
                    <div className="stat-icon"><i className="fa-solid fa-receipt"></i></div>
                    <div className="stat-info">
                      <h4>Bookings Revenue</h4>
                      <div className="stat-val">${totalRevenue.toFixed(2)}</div>
                    </div>
                  </div>
                  <div className="stat-card glass-panel-light">
                    <div className="stat-icon"><i className="fa-regular fa-calendar-check"></i></div>
                    <div className="stat-info">
                      <h4>Approved Stays</h4>
                      <div className="stat-val">{approvedBookingsCount} active</div>
                    </div>
                  </div>
                  <div className="stat-card glass-panel-light">
                    <div className="stat-icon"><i className="fa-solid fa-hourglass-half"></i></div>
                    <div className="stat-info">
                      <h4>Pending Requests</h4>
                      <div className="stat-val">{pendingBookingsCount} action</div>
                    </div>
                  </div>
                </div>
                
                <h3 style={{ fontSize: '1.25rem', marginBottom: '1rem', fontFamily: 'var(--font-display)' }}>Recent Booking Pipeline</h3>
                <div className="premium-table-wrapper">
                  <table className="premium-table">
                    <thead>
                      <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Staying Dates</th>
                        <th>Revenue</th>
                        <th>Status</th>
                      </tr>
                    </thead>
                    <tbody>
                      {bookings.slice(0, 4).map(b => (
                        <tr key={b.id}>
                          <td><strong>{b.id}</strong></td>
                          <td>{b.guestName}</td>
                          <td>{b.checkIn} to {b.checkOut}</td>
                          <td>${b.totalPrice.toFixed(2)}</td>
                          <td>
                            <span className={`badge ${b.status.toLowerCase()}`}>{b.status}</span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            )}
            
            {/* TAB 2: GUEST RESERVATION MANAGER */}
            {adminTab === 'bookings' && (
              <div>
                <div className="admin-panel-header">
                  <h2 className="admin-panel-title">Guest Booking Pipelines</h2>
                  <span className="badge pending">{pendingBookingsCount} Attention Required</span>
                </div>
                
                <div className="premium-table-wrapper">
                  <table className="premium-table">
                    <thead>
                      <tr>
                        <th>ID</th>
                        <th>Guest Details</th>
                        <th>Staying Dates</th>
                        <th>Guests Count</th>
                        <th>Estimated Revenue</th>
                        <th>Status</th>
                        <th>Approve/Reject</th>
                      </tr>
                    </thead>
                    <tbody>
                      {bookings.map(b => (
                        <tr key={b.id}>
                          <td><strong>{b.id}</strong></td>
                          <td>
                            <div>{b.guestName}</div>
                            <div style={{ fontSize: '0.75rem', color: 'var(--text-muted)' }}>{b.guestEmail}</div>
                          </td>
                          <td>{b.checkIn} to {b.checkOut}</td>
                          <td>{b.guestsCount} Guest{b.guestsCount !== 1 ? 's' : ''}</td>
                          <td>${b.totalPrice.toFixed(2)}</td>
                          <td>
                            <span className={`badge ${b.status.toLowerCase()}`}>{b.status}</span>
                          </td>
                          <td>
                            <div className="action-btn-group">
                              {b.status === "Pending" && (
                                <>
                                  <button 
                                    className="action-btn approve" 
                                    onClick={() => updateBookingStatus(b.id, 'Approved')}
                                    title="Approve Booking Request"
                                  >
                                    <i className="fa-solid fa-check"></i>
                                  </button>
                                  <button 
                                    className="action-btn deny" 
                                    onClick={() => updateBookingStatus(b.id, 'Denied')}
                                    title="Deny Booking Request"
                                  >
                                    <i className="fa-solid fa-xmark"></i>
                                  </button>
                                </>
                              )}
                              <button 
                                className="action-btn delete" 
                                onClick={() => deleteBooking(b.id)}
                                title="Delete Entry"
                              >
                                <i className="fa-solid fa-trash-can"></i>
                              </button>
                            </div>
                          </td>
                        </tr>
                      ))}
                      {bookings.length === 0 && (
                        <tr>
                          <td colSpan={7} style={{ textAlign: 'center', padding: '3rem' }}>
                            No active stays or booking requests registered.
                          </td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
              </div>
            )}
            
            {/* TAB 3: CALENDAR SYNC CHANNELS */}
            {adminTab === 'channels' && (
              <div>
                <div className="admin-panel-header">
                  <h2 className="admin-panel-title">Active Calendar Feed Integrations</h2>
                  <span>iCal/ICS Sync Pools</span>
                </div>
                
                <div className="premium-table-wrapper" style={{ marginBottom: '2.5rem' }}>
                  <table className="premium-table">
                    <thead>
                      <tr>
                        <th>Channel Identifier</th>
                        <th>ICS Endpoint Url</th>
                        <th>Last Sync Active</th>
                        <th>Verify</th>
                        <th>Disconnect</th>
                      </tr>
                    </thead>
                    <tbody>
                      {channels.map(chan => (
                        <tr key={chan.id}>
                          <td><strong>{chan.name}</strong></td>
                          <td style={{ fontSize: '0.75rem', maxWidth: '300px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={chan.url}>
                            {chan.url}
                          </td>
                          <td>{chan.lastSynced}</td>
                          <td>
                            <span style={{ color: '#8bb37e', fontSize: '0.8rem' }}>
                              <i className="fa-solid fa-circle-check" style={{ marginRight: '6px' }}></i> Active
                            </span>
                          </td>
                          <td>
                            <button 
                              className="action-btn delete" 
                              onClick={() => deleteChannel(chan.id)}
                              title="Delete sync channel"
                            >
                              <i className="fa-solid fa-trash-can"></i>
                            </button>
                          </td>
                        </tr>
                      ))}
                      {channels.length === 0 && (
                        <tr>
                          <td colSpan={5} style={{ textAlign: 'center', padding: '3rem' }}>
                            No connected external channels found. Direct sync inactive.
                          </td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
                
                <h3 style={{ fontSize: '1.25rem', marginBottom: '1rem', fontFamily: 'var(--font-display)' }}>Add External iCal Channel</h3>
                <form onSubmit={handleAddChannel} className="glass-panel-light" style={{ padding: '2rem' }}>
                  <div className="calc-grid">
                    <div className="form-group">
                      <label htmlFor="chan-name">Channel Platform Name</label>
                      <input 
                        type="text" 
                        id="chan-name" 
                        placeholder="e.g. Booking.com Sync"
                        value={newChannelName}
                        onChange={(e) => setNewChannelName(e.target.value)}
                        required
                      />
                    </div>
                    
                    <div className="form-group">
                      <label htmlFor="chan-url">iCal Feed URL (.ics)</label>
                      <input 
                        type="url" 
                        id="chan-url" 
                        placeholder="https://example.com/calendar.ics"
                        value={newChannelUrl}
                        onChange={(e) => setNewChannelUrl(e.target.value)}
                        required
                      />
                    </div>
                  </div>
                  
                  {channelMessage && (
                    <div style={{ color: '#8bb37e', fontSize: '0.85rem', marginBottom: '1.25rem' }}>
                      <i className="fa-solid fa-circle-check"></i> {channelMessage}
                    </div>
                  )}
                  
                  <button type="submit" className="btn-premium">
                    Add Sync Channel <i className="fa-solid fa-plus"></i>
                  </button>
                </form>
              </div>
            )}
            
            {/* TAB 4: PROPERTY CONFIGURATIONS */}
            {adminTab === 'settings' && (
              <div>
                <div className="admin-panel-header">
                  <h2 className="admin-panel-title">Cottage Details Configurator</h2>
                  <span>Push live updates to property listings</span>
                </div>
                
                <form onSubmit={handleSaveSettings}>
                  <div className="calc-grid">
                    <div className="form-group">
                      <label htmlFor="prop-title">Listing Display Title</label>
                      <input 
                        type="text" 
                        id="prop-title"
                        value={tempTitle}
                        onChange={(e) => setTempTitle(e.target.value)}
                        required
                      />
                    </div>
                    
                    <div className="form-group" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
                      <div className="form-group">
                        <label htmlFor="prop-rate">Nightly Base Rate ($)</label>
                        <input 
                          type="number" 
                          id="prop-rate"
                          value={tempRate}
                          onChange={(e) => setTempRate(parseInt(e.target.value))}
                          required
                        />
                      </div>
                      
                      <div className="form-group">
                        <label htmlFor="prop-cleaning">Linen Fee ($)</label>
                        <input 
                          type="number" 
                          id="prop-cleaning"
                          value={tempCleaning}
                          onChange={(e) => setTempCleaning(parseInt(e.target.value))}
                          required
                        />
                      </div>
                    </div>
                  </div>
                  
                  <div className="form-group">
                    <label htmlFor="prop-desc">Property Story & Overview</label>
                    <textarea 
                      id="prop-desc" 
                      rows={5}
                      value={tempDesc}
                      onChange={(e) => setTempDesc(e.target.value)}
                      required
                    ></textarea>
                  </div>
                  
                  {settingsMessage && (
                    <div style={{ color: '#8bb37e', fontSize: '0.85rem', marginBottom: '1.25rem' }}>
                      <i className="fa-solid fa-circle-check"></i> {settingsMessage}
                    </div>
                  )}
                  
                  <button type="submit" className="btn-premium">
                    Push Live Updates <i className="fa-solid fa-cloud-arrow-up"></i>
                  </button>
                </form>
              </div>
            )}
            
          </div>
        </div>
      </div>
    </section>
  );
}

// --- MOUNT THE REACT APPLICATION ---
const container = document.getElementById('root');
if (container) {
  const root = (window as any).ReactDOM.createRoot(container);
  root.render(<App />);
}
