'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';

interface ImageRecord {
  id: number;
  filename: string;
  data: string;
  uploaded_at: string;
}

interface Room {
  id: number;
  name: string;
  description: string;
  price: string;
  photos: string[];
  active: boolean;
  sort_order: number;
}

interface RoomForm {
  id?: number;
  name: string;
  description: string;
  price: string;
  photos: string | string[];
  active: boolean;
  sort_order: number;
}

interface MenuItem {
  id: number;
  category: string;
  name: string;
  description: string;
  price: string;
  is_daily_special: boolean;
  active: boolean;
  sort_order: number;
}

interface Place {
  id: number;
  name: string;
  description: string;
  photo: string | null;
  distance_km: string | null;
  visit_time: string | null;
  suggestion: string | null;
  active: boolean;
  sort_order: number;
}

interface Review {
  id: number;
  author_name: string;
  rating: number;
  text: string;
  approved: boolean;
}

interface User {
  id: number;
  username: string;
  role: 'admin' | 'user';
}

interface Slide {
  id: number;
  title: string | null;
  subtitle: string | null;
  image_id: number | null;
  image_url: string | null;
  active: boolean;
  sort_order: number;
}

interface CalendarEvent {
  id: number;
  date: string;
  title: string;
  type: 'holiday' | 'season' | 'weather' | 'event';
  description: string | null;
  color: string | null;
  active: boolean;
}

const gold = '#E8A849';
const navy = '#001321';
const warm = '#a6683c';

export default function AdminPage() {
  const router = useRouter();
  const [images, setImages] = useState<ImageRecord[]>([]);
  const [count, setCount] = useState(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);
  const [logoUrl, setLogoUrl] = useState('');
  const [faviconUrl, setFaviconUrl] = useState('');
  const [tagline, setTagline] = useState('Hotel · Restaurant · Andean Highlands');

  const [rooms, setRooms] = useState<Room[]>([]);
  const [roomForm, setRoomForm] = useState<RoomForm>({ name: '', description: '', price: '', photos: '', active: true, sort_order: 0 });
  const [editingRoom, setEditingRoom] = useState<number | null>(null);

  const [menu, setMenu] = useState<MenuItem[]>([]);
  const [menuForm, setMenuForm] = useState<Partial<MenuItem>>({ category: '', name: '', description: '', price: '', is_daily_special: false, active: true, sort_order: 0 });
  const [editingMenu, setEditingMenu] = useState<number | null>(null);

  const [places, setPlaces] = useState<Place[]>([]);
  const [placeForm, setPlaceForm] = useState<Partial<Place>>({ name: '', description: '', photo: '', distance_km: '', visit_time: '', suggestion: '', active: true, sort_order: 0 });
  const [editingPlace, setEditingPlace] = useState<number | null>(null);

  const [reviews, setReviews] = useState<Review[]>([]);

  const [users, setUsers] = useState<User[]>([]);
  const [userForm, setUserForm] = useState({ username: '', password: '', role: 'user' as 'admin' | 'user' });

  const [slides, setSlides] = useState<Slide[]>([]);
  const [slideForm, setSlideForm] = useState<Partial<Slide>>({ title: '', subtitle: '', image_id: null, image_url: '', active: true, sort_order: 0 });
  const [editingSlide, setEditingSlide] = useState<number | null>(null);

  const [events, setEvents] = useState<CalendarEvent[]>([]);
  const [eventForm, setEventForm] = useState<Partial<CalendarEvent>>({ date: '', title: '', type: 'event', description: '', color: '#E8A849', active: true });
  const [editingEvent, setEditingEvent] = useState<number | null>(null);

  const [footer, setFooter] = useState({
    facebook_url: '', instagram_url: '', whatsapp_url: '', address: '', phone: '', email: '',
  });

  useEffect(() => {
    fetch('/api/admin/images', { credentials: 'same-origin' })
      .then(async (res) => {
        if (!res.ok) {
          if (res.status === 401) { router.push('/login'); return; }
          throw new Error('Failed to load images');
        }
        const data = await res.json();
        setImages(data.images || []);
        setCount(data.count || 0);
      })
      .catch((err) => setError(err.message));

    fetch('/api/rooms').then((r) => r.json()).then((j) => setRooms(j.data || [])).catch(() => {});
    fetch('/api/menu').then((r) => r.json()).then((j) => setMenu(j.data || [])).catch(() => {});
    fetch('/api/places').then((r) => r.json()).then((j) => setPlaces(j.data || [])).catch(() => {});
    fetch('/api/admin/reviews', { credentials: 'same-origin' }).then((r) => r.json()).then((j) => setReviews(j.data || [])).catch(() => {});
    fetch('/api/admin/users', { credentials: 'same-origin' }).then((r) => r.json()).then((j) => setUsers(j.data || [])).catch(() => {});
    fetch('/api/slides').then((r) => r.json()).then((j) => setSlides(j.data || [])).catch(() => {});
    fetch('/api/calendar_events').then((r) => r.json()).then((j) => setEvents(j.data || [])).catch(() => {});

    fetch('/api/site-assets').then((res) => res.json()).then((json) => {
      const c = json.data || {};
      setFooter({
        facebook_url: c.facebook_url || '', instagram_url: c.instagram_url || '', whatsapp_url: c.whatsapp_url || '',
        address: c.address || '', phone: c.phone || '', email: c.email || '',
      });
      if (c.logo) setLogoUrl(c.logo);
      if (c.favicon) setFaviconUrl(c.favicon);
      if (c.tagline) setTagline(c.tagline);
    }).catch(() => {});

    setLoading(false);
  }, [router]);

  const notify = (msg: string) => {
    setMessage(msg);
    setTimeout(() => setMessage(null), 4000);
  };

  const updateAsset = async (key: string, value: string) => {
    const res = await fetch('/api/site-assets', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ key, value }),
      credentials: 'same-origin',
    });
    if (!res.ok) { setError('Failed to save ' + key); return; }
    notify(`${key} updated.`);
  };

  const saveFooter = async () => {
    const res = await fetch('/api/site-assets', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ values: footer }),
      credentials: 'same-origin',
    });
    if (!res.ok) { setError('Failed to save footer'); return; }
    notify('Footer info updated.');
  };

  const handleUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files) return;
    Array.from(files).forEach((file) => {
      const reader = new FileReader();
      reader.onload = async () => {
        const data = reader.result as string;
        const res = await fetch('/api/admin/images', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ filename: file.name, data }),
          credentials: 'same-origin',
        });
        if (!res.ok) { setError('Upload failed'); return; }
        const result = await res.json();
        setImages((prev) => [{ ...result.image, data }, ...prev]);
        setCount((prev) => prev + 1);
      };
      reader.readAsDataURL(file);
    });
    e.target.value = '';
  };

  const handleDelete = async (id: number) => {
    const res = await fetch(`/api/admin/images?id=${id}`, { method: 'DELETE', credentials: 'same-origin' });
    if (res.ok) {
      setImages((prev) => prev.filter((img) => img.id !== id));
      setCount((prev) => prev - 1);
    }
  };

  const api = async (url: string, method: string, body?: object) => {
    const res = await fetch(url, {
      method,
      headers: { 'Content-Type': 'application/json' },
      credentials: 'same-origin',
      body: body ? JSON.stringify(body) : undefined,
    });
    if (!res.ok) {
      const j = await res.json().catch(() => ({}));
      throw new Error(j.error || 'Request failed');
    }
    return res.json();
  };

  const saveRoom = async (e: React.FormEvent) => {
    e.preventDefault();
    const photosValue = roomForm.photos || [];
    const photosArray: string[] = typeof photosValue === 'string' ? (photosValue as unknown as string).split(',').map((s: string) => s.trim()).filter(Boolean) : photosValue;
    const payload = { ...roomForm, photos: photosArray, active: roomForm.active !== false, sort_order: roomForm.sort_order || 0 };
    if (editingRoom) {
      await api(`/api/rooms/${editingRoom}`, 'PUT', payload);
      setRooms((prev) => prev.map((r) => (r.id === editingRoom ? { ...r, ...payload } as Room : r)));
      setEditingRoom(null);
    } else {
      const json = await api('/api/rooms', 'POST', payload);
      setRooms((prev) => [...prev, json.data]);
    }
    setRoomForm({ name: '', description: '', price: '', photos: '', active: true, sort_order: 0 });
    notify('Room saved.');
  };

  const editRoom = (r: Room) => { setRoomForm({ ...r, photos: r.photos?.join(', ') || '' }); setEditingRoom(r.id); };
  const deleteRoom = async (id: number) => { await api(`/api/rooms/${id}`, 'DELETE'); setRooms((prev) => prev.filter((r) => r.id !== id)); };

  const saveMenu = async (e: React.FormEvent) => {
    e.preventDefault();
    const payload = { ...menuForm, active: menuForm.active !== false, sort_order: menuForm.sort_order || 0 };
    if (editingMenu) {
      await api(`/api/menu/${editingMenu}`, 'PUT', payload);
      setMenu((prev) => prev.map((m) => (m.id === editingMenu ? { ...m, ...payload } as MenuItem : m)));
      setEditingMenu(null);
    } else {
      const json = await api('/api/menu', 'POST', payload);
      setMenu((prev) => [...prev, json.data]);
    }
    setMenuForm({ category: '', name: '', description: '', price: '', is_daily_special: false, active: true, sort_order: 0 });
    notify('Menu item saved.');
  };

  const editMenu = (m: MenuItem) => { setMenuForm({ ...m }); setEditingMenu(m.id); };
  const deleteMenu = async (id: number) => { await api(`/api/menu/${id}`, 'DELETE'); setMenu((prev) => prev.filter((m) => m.id !== id)); };

  const savePlace = async (e: React.FormEvent) => {
    e.preventDefault();
    const payload = { ...placeForm, active: placeForm.active !== false, sort_order: placeForm.sort_order || 0 };
    if (editingPlace) {
      await api(`/api/places/${editingPlace}`, 'PUT', payload);
      setPlaces((prev) => prev.map((p) => (p.id === editingPlace ? { ...p, ...payload } as Place : p)));
      setEditingPlace(null);
    } else {
      const json = await api('/api/places', 'POST', payload);
      setPlaces((prev) => [...prev, json.data]);
    }
    setPlaceForm({ name: '', description: '', photo: '', distance_km: '', visit_time: '', suggestion: '', active: true, sort_order: 0 });
    notify('Place saved.');
  };

  const editPlace = (p: Place) => { setPlaceForm({ ...p }); setEditingPlace(p.id); };
  const deletePlace = async (id: number) => { await api(`/api/places/${id}`, 'DELETE'); setPlaces((prev) => prev.filter((p) => p.id !== id)); };

  const approveReview = async (id: number) => {
    await api(`/api/admin/reviews/${id}`, 'PUT', { approved: true });
    setReviews((prev) => prev.map((r) => (r.id === id ? { ...r, approved: true } : r)));
  };

  const deleteReview = async (id: number) => { await api(`/api/admin/reviews/${id}`, 'DELETE'); setReviews((prev) => prev.filter((r) => r.id !== id)); };

  const saveUser = async (e: React.FormEvent) => {
    e.preventDefault();
    const json = await api('/api/admin/users', 'POST', userForm);
    setUsers((prev) => [...prev, json.user]);
    setUserForm({ username: '', password: '', role: 'user' });
    notify('User created.');
  };

  const deleteUser = async (id: number) => { await api(`/api/admin/users/${id}`, 'DELETE'); setUsers((prev) => prev.filter((u) => u.id !== id)); };

  const saveSlide = async (e: React.FormEvent) => {
    e.preventDefault();
    const payload = { ...slideForm, active: slideForm.active !== false, sort_order: slideForm.sort_order || 0 };
    if (editingSlide) {
      await api(`/api/slides/${editingSlide}`, 'PUT', payload);
      setSlides((prev) => prev.map((s) => (s.id === editingSlide ? { ...s, ...payload } as Slide : s)));
      setEditingSlide(null);
    } else {
      const json = await api('/api/slides', 'POST', payload);
      setSlides((prev) => [...prev, json.data]);
    }
    setSlideForm({ title: '', subtitle: '', image_id: null, image_url: '', active: true, sort_order: 0 });
    notify('Slide saved.');
  };

  const editSlide = (s: Slide) => { setSlideForm({ ...s }); setEditingSlide(s.id); };
  const deleteSlide = async (id: number) => { await api(`/api/slides/${id}`, 'DELETE'); setSlides((prev) => prev.filter((s) => s.id !== id)); };

  const saveEvent = async (e: React.FormEvent) => {
    e.preventDefault();
    const payload = { ...eventForm, active: eventForm.active !== false };
    if (editingEvent) {
      await api(`/api/calendar_events/${editingEvent}`, 'PUT', payload);
      setEvents((prev) => prev.map((ev) => (ev.id === editingEvent ? { ...ev, ...payload } as CalendarEvent : ev)));
      setEditingEvent(null);
    } else {
      const json = await api('/api/calendar_events', 'POST', payload);
      setEvents((prev) => [...prev, json.data]);
    }
    setEventForm({ date: '', title: '', type: 'event', description: '', color: '#E8A849', active: true });
    notify('Calendar event saved.');
  };

  const editEvent = (ev: CalendarEvent) => { setEventForm({ ...ev }); setEditingEvent(ev.id); };
  const deleteEvent = async (id: number) => { await api(`/api/calendar_events/${id}`, 'DELETE'); setEvents((prev) => prev.filter((ev) => ev.id !== id)); };

  if (loading) {
    return (
      <main style={{ padding: '2rem', color: warm, fontSize: '18px' }}>
        <p>Loading admin...</p>
      </main>
    );
  }

  return (
    <main style={{ padding: '2rem', maxWidth: '80rem', margin: '0 auto' }}>
      <h1 style={{ fontSize: 'clamp(28px, 4vw, 42px)', fontWeight: 400, fontStyle: 'italic', color: navy, margin: '0 0 0.5rem' }}>
        Admin Portal
      </h1>
      <p style={{ color: '#555', marginBottom: '1.5rem' }}>
        Total uploaded images: <strong style={{ color: warm }}>{count}</strong>
      </p>
      {error && <p style={{ color: '#c23b22', marginBottom: '1rem' }}>{error}</p>}
      {message && <p style={{ color: '#3b7a22', marginBottom: '1rem' }}>{message}</p>}

      <Section title="Brand Assets">
        <div style={{ display: 'grid', gap: '1rem', gridTemplateColumns: '1fr auto', alignItems: 'end' }}>
          <Text label="Navbar logo" value={logoUrl} onChange={setLogoUrl} />
          <Button onClick={() => updateAsset('logo', logoUrl)} disabled={!logoUrl}>Save logo</Button>
          <Text label="Favicon" value={faviconUrl} onChange={setFaviconUrl} />
          <Button onClick={() => updateAsset('favicon', faviconUrl)} disabled={!faviconUrl}>Save favicon</Button>
          <Text label="Homepage tagline" value={tagline} onChange={setTagline} />
          <Button onClick={() => updateAsset('tagline', tagline)} disabled={!tagline}>Save tagline</Button>
        </div>
        <p style={{ margin: '1rem 0 0', fontSize: '13px', color: '#777' }}>
          Tip: click an uploaded gallery image to preview, copy its data URL, and paste it above.
        </p>
      </Section>

      <Section title="Footer / Contact">
        <div style={{ display: 'grid', gap: '1rem', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))' }}>
          <Text label="Facebook URL" value={footer.facebook_url} onChange={(v) => setFooter({ ...footer, facebook_url: v })} />
          <Text label="Instagram URL" value={footer.instagram_url} onChange={(v) => setFooter({ ...footer, instagram_url: v })} />
          <Text label="WhatsApp URL" value={footer.whatsapp_url} onChange={(v) => setFooter({ ...footer, whatsapp_url: v })} />
          <Text label="Address" value={footer.address} onChange={(v) => setFooter({ ...footer, address: v })} />
          <Text label="Phone" value={footer.phone} onChange={(v) => setFooter({ ...footer, phone: v })} />
          <Text label="Email" value={footer.email} onChange={(v) => setFooter({ ...footer, email: v })} />
        </div>
        <div style={{ marginTop: '1rem' }}>
          <Button onClick={saveFooter}>Save footer info</Button>
        </div>
      </Section>

      <Section title="Image Gallery">
        <label style={{ display: 'inline-flex', alignItems: 'center', gap: '0.5rem', padding: '0.75rem 1.25rem', background: gold, color: navy, borderRadius: '999px', cursor: 'pointer', fontWeight: 600, marginBottom: '1.5rem' }}>
          + Upload images
          <input type="file" accept="image/*" multiple onChange={handleUpload} style={{ display: 'none' }} />
        </label>
        {images.length === 0 ? (
          <p style={{ color: '#777' }}>No images uploaded yet.</p>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: '1.25rem' }}>
            {images.map((img) => (
              <div
                key={img.id}
                style={{
                  borderRadius: '16px',
                  overflow: 'hidden',
                  display: 'flex',
                  flexDirection: 'column',
                  background: '#f5f0e8',
                  transition: 'transform 200ms, box-shadow 200ms',
                  cursor: 'pointer',
                }}
                onMouseEnter={(e) => { e.currentTarget.style.transform = 'scale(1.03)'; e.currentTarget.style.boxShadow = '0 8px 22px rgba(0,0,0,0.12)'; }}
                onMouseLeave={(e) => { e.currentTarget.style.transform = 'scale(1)'; e.currentTarget.style.boxShadow = 'none'; }}
                onClick={() => { navigator.clipboard.writeText(img.data); notify('Image URL copied.'); }}
              >
                <img src={img.data} alt={img.filename} style={{ width: '100%', height: '180px', objectFit: 'cover' }} />
                <button
                  onClick={(e) => { e.stopPropagation(); handleDelete(img.id); }}
                  style={{ padding: '0.65rem', background: '#c23b22', color: '#fff', border: 'none', cursor: 'pointer', fontSize: '14px', fontWeight: 600 }}
                >
                  Delete
                </button>
              </div>
            ))}
          </div>
        )}
      </Section>

      <Section title="Homepage Slideshow">
        <form onSubmit={saveSlide} style={{ display: 'grid', gap: '1rem', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', marginBottom: '1.5rem' }}>
          <Text label="Title" value={slideForm.title || ''} onChange={(v) => setSlideForm({ ...slideForm, title: v })} />
          <Text label="Subtitle" value={slideForm.subtitle || ''} onChange={(v) => setSlideForm({ ...slideForm, subtitle: v })} />
          <Text label="Image URL (or pick image ID below)" value={slideForm.image_url || ''} onChange={(v) => setSlideForm({ ...slideForm, image_url: v })} />
          <Number label="Sort order" value={slideForm.sort_order ?? 0} onChange={(v) => setSlideForm({ ...slideForm, sort_order: parseInt(v || '0', 10) })} />
          <ImageSelect label="Gallery image" images={images} value={slideForm.image_id ?? ''} onChange={(v) => setSlideForm({ ...slideForm, image_id: v ? parseInt(v, 10) : null })} />
          <label style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontSize: '14px', color: '#555' }}>
            <input type="checkbox" checked={slideForm.active !== false} onChange={(e) => setSlideForm({ ...slideForm, active: e.target.checked })} />
            Active
          </label>
          <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'end' }}>
            <Button type="submit">{editingSlide ? 'Update slide' : 'Add slide'}</Button>
            {editingSlide && <SecondaryButton onClick={() => { setEditingSlide(null); setSlideForm({ title: '', subtitle: '', image_id: null, image_url: '', active: true, sort_order: 0 }); }}>Cancel</SecondaryButton>}
          </div>
        </form>
        <ListTable rows={slides.map((s) => [s.title || '(untitled)', s.active ? 'On' : 'Off', `#${s.sort_order}`])} onEdit={(i) => editSlide(slides[i])} onDelete={(i) => deleteSlide(slides[i].id)} />
      </Section>

      <Section title="Calendar Events">
        <form onSubmit={saveEvent} style={{ display: 'grid', gap: '1rem', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', marginBottom: '1.5rem' }}>
          <Text label="Date" type="date" value={eventForm.date || ''} onChange={(v) => setEventForm({ ...eventForm, date: v })} />
          <Text label="Title" value={eventForm.title || ''} onChange={(v) => setEventForm({ ...eventForm, title: v })} />
          <label style={{ display: 'flex', flexDirection: 'column', gap: '0.4rem', fontSize: '14px', color: '#555' }}>
            Type
            <select value={eventForm.type || 'event'} onChange={(e) => setEventForm({ ...eventForm, type: e.target.value as CalendarEvent['type'] })} style={{ padding: '0.6rem 0.8rem', borderRadius: '10px', border: '1px solid rgba(1,13,30,0.18)' }}>
              <option value="holiday">Holiday</option>
              <option value="season">Season</option>
              <option value="weather">Weather</option>
              <option value="event">Event</option>
            </select>
          </label>
          <Text label="Color" value={eventForm.color || '#E8A849'} onChange={(v) => setEventForm({ ...eventForm, color: v })} />
          <Text label="Description" value={eventForm.description || ''} onChange={(v) => setEventForm({ ...eventForm, description: v })} />
          <label style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontSize: '14px', color: '#555' }}>
            <input type="checkbox" checked={eventForm.active !== false} onChange={(e) => setEventForm({ ...eventForm, active: e.target.checked })} />
            Active
          </label>
          <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'end' }}>
            <Button type="submit">{editingEvent ? 'Update event' : 'Add event'}</Button>
            {editingEvent && <SecondaryButton onClick={() => { setEditingEvent(null); setEventForm({ date: '', title: '', type: 'event', description: '', color: '#E8A849', active: true }); }}>Cancel</SecondaryButton>}
          </div>
        </form>
        <ListTable rows={events.map((ev) => [ev.date, ev.title, ev.type, ev.active ? 'On' : 'Off'])} onEdit={(i) => editEvent(events[i])} onDelete={(i) => deleteEvent(events[i].id)} />
      </Section>

      <Section title="Rooms">
        <form onSubmit={saveRoom} style={{ display: 'grid', gap: '1rem', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', marginBottom: '1.5rem' }}>
          <Text label="Name" value={roomForm.name || ''} onChange={(v) => setRoomForm({ ...roomForm, name: v })} />
          <Text label="Price / night" value={roomForm.price || ''} onChange={(v) => setRoomForm({ ...roomForm, price: v })} />
          <Text label="Photos (comma-separated URLs)" value={typeof roomForm.photos === 'string' ? roomForm.photos : roomForm.photos.join(', ')} onChange={(v) => setRoomForm({ ...roomForm, photos: v })} />
          <Number label="Sort order" value={roomForm.sort_order ?? 0} onChange={(v) => setRoomForm({ ...roomForm, sort_order: parseInt(v || '0', 10) })} />
          <Text label="Description" value={roomForm.description || ''} onChange={(v) => setRoomForm({ ...roomForm, description: v })} />
          <label style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontSize: '14px', color: '#555' }}>
            <input type="checkbox" checked={roomForm.active !== false} onChange={(e) => setRoomForm({ ...roomForm, active: e.target.checked })} />
            Active
          </label>
          <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'end' }}>
            <Button type="submit">{editingRoom ? 'Update room' : 'Add room'}</Button>
            {editingRoom && <SecondaryButton onClick={() => { setEditingRoom(null); setRoomForm({ name: '', description: '', price: '', photos: '', active: true, sort_order: 0 }); }}>Cancel</SecondaryButton>}
          </div>
        </form>
        <ListTable rows={rooms.map((r) => [r.name, `$${r.price}`, r.description.slice(0, 60), r.active ? 'On' : 'Off', `#${r.sort_order}`])} onEdit={(i) => editRoom(rooms[i])} onDelete={(i) => deleteRoom(rooms[i].id)} />
      </Section>

      <Section title="Menu">
        <form onSubmit={saveMenu} style={{ display: 'grid', gap: '1rem', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', marginBottom: '1.5rem' }}>
          <Text label="Category" value={menuForm.category || ''} onChange={(v) => setMenuForm({ ...menuForm, category: v })} />
          <Text label="Name" value={menuForm.name || ''} onChange={(v) => setMenuForm({ ...menuForm, name: v })} />
          <Text label="Price" value={menuForm.price || ''} onChange={(v) => setMenuForm({ ...menuForm, price: v })} />
          <Number label="Sort order" value={menuForm.sort_order ?? 0} onChange={(v) => setMenuForm({ ...menuForm, sort_order: parseInt(v || '0', 10) })} />
          <label style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontSize: '14px', color: '#555' }}>
            <input type="checkbox" checked={menuForm.is_daily_special || false} onChange={(e) => setMenuForm({ ...menuForm, is_daily_special: e.target.checked })} />
            Daily special
          </label>
          <label style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontSize: '14px', color: '#555' }}>
            <input type="checkbox" checked={menuForm.active !== false} onChange={(e) => setMenuForm({ ...menuForm, active: e.target.checked })} />
            Active
          </label>
          <Text label="Description" value={menuForm.description || ''} onChange={(v) => setMenuForm({ ...menuForm, description: v })} />
          <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'end' }}>
            <Button type="submit">{editingMenu ? 'Update item' : 'Add item'}</Button>
            {editingMenu && <SecondaryButton onClick={() => { setEditingMenu(null); setMenuForm({ category: '', name: '', description: '', price: '', is_daily_special: false, active: true, sort_order: 0 }); }}>Cancel</SecondaryButton>}
          </div>
        </form>
        <ListTable rows={menu.map((m) => [m.category, m.name, `$${m.price}`, m.is_daily_special ? '★ Daily' : '', m.active ? 'On' : 'Off', `#${m.sort_order}`])} onEdit={(i) => editMenu(menu[i])} onDelete={(i) => deleteMenu(menu[i].id)} />
      </Section>

      <Section title="Landscape Places">
        <form onSubmit={savePlace} style={{ display: 'grid', gap: '1rem', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', marginBottom: '1.5rem' }}>
          <Text label="Name" value={placeForm.name || ''} onChange={(v) => setPlaceForm({ ...placeForm, name: v })} />
          <Text label="Distance (km)" value={placeForm.distance_km || ''} onChange={(v) => setPlaceForm({ ...placeForm, distance_km: v })} />
          <Text label="Visit time" value={placeForm.visit_time || ''} onChange={(v) => setPlaceForm({ ...placeForm, visit_time: v })} />
          <Text label="Photo URL" value={placeForm.photo || ''} onChange={(v) => setPlaceForm({ ...placeForm, photo: v })} />
          <Number label="Sort order" value={placeForm.sort_order ?? 0} onChange={(v) => setPlaceForm({ ...placeForm, sort_order: parseInt(v || '0', 10) })} />
          <Text label="Description" value={placeForm.description || ''} onChange={(v) => setPlaceForm({ ...placeForm, description: v })} />
          <Text label="Suggestion" value={placeForm.suggestion || ''} onChange={(v) => setPlaceForm({ ...placeForm, suggestion: v })} />
          <label style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontSize: '14px', color: '#555' }}>
            <input type="checkbox" checked={placeForm.active !== false} onChange={(e) => setPlaceForm({ ...placeForm, active: e.target.checked })} />
            Active
          </label>
          <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'end' }}>
            <Button type="submit">{editingPlace ? 'Update place' : 'Add place'}</Button>
            {editingPlace && <SecondaryButton onClick={() => { setEditingPlace(null); setPlaceForm({ name: '', description: '', photo: '', distance_km: '', visit_time: '', suggestion: '', active: true, sort_order: 0 }); }}>Cancel</SecondaryButton>}
          </div>
        </form>
        <ListTable rows={places.map((p) => [p.name, `${p.distance_km || ''} km`, p.description.slice(0, 60), p.active ? 'On' : 'Off', `#${p.sort_order}`])} onEdit={(i) => editPlace(places[i])} onDelete={(i) => deletePlace(places[i].id)} />
      </Section>

      <Section title="Pending Reviews">
        {reviews.length === 0 ? <p style={{ color: '#777' }}>No pending reviews.</p> : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
            {reviews.map((r) => (
              <div key={r.id} style={{ background: '#fff', padding: '1rem 1.25rem', borderRadius: '12px', boxShadow: '0 1px 3px rgba(1,13,30,0.06)' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '0.5rem' }}>
                  <strong>{r.author_name}</strong>
                  <span style={{ color: gold }}>{'★'.repeat(r.rating)}{'☆'.repeat(5 - r.rating)}</span>
                </div>
                <p style={{ margin: '0 0 0.75rem', color: '#555' }}>{r.text}</p>
                <div style={{ display: 'flex', gap: '0.5rem' }}>
                  {!r.approved && <Button onClick={() => approveReview(r.id)}>Approve</Button>}
                  <DangerButton onClick={() => deleteReview(r.id)}>Delete</DangerButton>
                </div>
              </div>
            ))}
          </div>
        )}
      </Section>

      <Section title="Users">
        <form onSubmit={saveUser} style={{ display: 'grid', gap: '1rem', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', marginBottom: '1.5rem' }}>
          <Text label="Username" value={userForm.username} onChange={(v) => setUserForm({ ...userForm, username: v })} />
          <Text label="Password" value={userForm.password} type="password" onChange={(v) => setUserForm({ ...userForm, password: v })} />
          <label style={{ display: 'flex', flexDirection: 'column', gap: '0.4rem', fontSize: '14px', color: '#555' }}>
            Role
            <select value={userForm.role} onChange={(e) => setUserForm({ ...userForm, role: e.target.value as 'admin' | 'user' })} style={{ padding: '0.6rem 0.8rem', borderRadius: '10px', border: '1px solid rgba(1,13,30,0.18)' }}>
              <option value="user">User</option>
              <option value="admin">Admin</option>
            </select>
          </label>
          <div style={{ display: 'flex', alignItems: 'end' }}>
            <Button type="submit">Create user</Button>
          </div>
        </form>
        <ListTable rows={users.map((u) => [u.username, u.role])} onDelete={(i) => deleteUser(users[i].id)} />
      </Section>
    </main>
  );
}

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <section style={{ marginBottom: '2.5rem', padding: '1.5rem', background: '#f5f0e8', borderRadius: '16px' }}>
      <h2 style={{ fontSize: '20px', color: navy, margin: '0 0 1rem' }}>{title}</h2>
      {children}
    </section>
  );
}

function Text({ label, value, onChange, type = 'text' }: { label: string; value: string; onChange: (v: string) => void; type?: string }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: '0.4rem', fontSize: '14px', color: '#555' }}>
      {label}
      <input
        type={type}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        style={{ padding: '0.6rem 0.8rem', borderRadius: '10px', border: '1px solid rgba(1,13,30,0.18)' }}
      />
    </label>
  );
}

function Number({ label, value, onChange }: { label: string; value: number; onChange: (v: string) => void }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: '0.4rem', fontSize: '14px', color: '#555' }}>
      {label}
      <input
        type="number"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        style={{ padding: '0.6rem 0.8rem', borderRadius: '10px', border: '1px solid rgba(1,13,30,0.18)' }}
      />
    </label>
  );
}

function ImageSelect({ label, images, value, onChange }: { label: string; images: ImageRecord[]; value: string | number; onChange: (v: string) => void }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: '0.4rem', fontSize: '14px', color: '#555' }}>
      {label}
      <select value={value} onChange={(e) => onChange(e.target.value)} style={{ padding: '0.6rem 0.8rem', borderRadius: '10px', border: '1px solid rgba(1,13,30,0.18)' }}>
        <option value="">None (use URL)</option>
        {images.map((img) => (
          <option key={img.id} value={img.id}>
            #{img.id} {img.filename}
          </option>
        ))}
      </select>
    </label>
  );
}

function Button({ children, onClick, type = 'button', disabled = false }: { children: React.ReactNode; onClick?: () => void; type?: 'button' | 'submit'; disabled?: boolean }) {
  return (
    <button
      type={type}
      onClick={onClick}
      disabled={disabled}
      style={{
        padding: '0.7rem 1.2rem',
        background: disabled ? '#ccc' : gold,
        color: navy,
        border: 'none',
        borderRadius: '999px',
        cursor: disabled ? 'not-allowed' : 'pointer',
        fontWeight: 600,
        whiteSpace: 'nowrap',
      }}
    >
      {children}
    </button>
  );
}

function SecondaryButton({ children, onClick }: { children: React.ReactNode; onClick: () => void }) {
  return (
    <button
      onClick={onClick}
      style={{ padding: '0.7rem 1.2rem', background: 'transparent', color: warm, border: `1.5px solid ${warm}`, borderRadius: '999px', cursor: 'pointer', fontWeight: 600, whiteSpace: 'nowrap' }}
    >
      {children}
    </button>
  );
}

function DangerButton({ children, onClick }: { children: React.ReactNode; onClick: () => void }) {
  return (
    <button
      onClick={onClick}
      style={{ padding: '0.5rem 1rem', background: '#c23b22', color: '#fff', border: 'none', borderRadius: '999px', cursor: 'pointer', fontWeight: 600, fontSize: '13px' }}
    >
      {children}
    </button>
  );
}

function ListTable({ rows, onEdit, onDelete }: { rows: string[][]; onEdit?: (index: number) => void; onDelete: (index: number) => void }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
      {rows.map((row, i) => (
        <div key={i} style={{ background: '#fff', padding: '0.9rem 1.1rem', borderRadius: '12px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: '1rem' }}>
          <div style={{ display: 'flex', gap: '1rem', flexWrap: 'wrap', color: navy }}>
            {row.map((cell, j) => <span key={j}>{cell}</span>)}
          </div>
          <div style={{ display: 'flex', gap: '0.5rem', flexShrink: 0 }}>
            {onEdit && <Button onClick={() => onEdit(i)}>Edit</Button>}
            <DangerButton onClick={() => onDelete(i)}>Delete</DangerButton>
          </div>
        </div>
      ))}
    </div>
  );
}
