/* global React, ReactDOM,
   A7Logo, Icon, Button, ToastProvider, useToast, Modal,
   Calendar, BookingFlow,
   NavBar, Hero, CalendarSection, ViviloDeNuevo, Servicios, Ubicacion, Footer, MobileMenu,
   useTweaks, TweaksPanel, TweakSection, TweakSlider, TweakToggle, TweakRadio, TweakSelect, TweakText, TweakNumber, TweakColor, TweakButton,
   initFirebase, saveBooking, getBookings, getAllBookingsForDate, checkAvailability
*/

// ===========================================================
// Área 7 — Main app
// ===========================================================

const { useState: useStateApp, useEffect: useEffectApp, useMemo: useMemoApp, useRef: useRefApp } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "name": "ÁREA 7",
  "tagline": "Una cancha de fútbol 7 bien futbolera en San Carlos. Reservá tu turno en menos de 1 minuto y dejá todo en la cancha.",
  "accentName": "A7 mint",
  "viewport": "auto",
  "density": "comfortable",
  "priceF5": 18000,
  "priceF7": 26000
}/*EDITMODE-END*/;

const ACCENT_PRESETS = {
  'A7 mint':       { c: '#5af7a9', ink: '#001a0e' },
  'Draftea emerald': { c: '#34d399', ink: '#001a0e' },
  'Lima':          { c: '#d2ff72', ink: '#0a1100' },
  'Cyan':          { c: '#67e8f9', ink: '#001a1f' },
};

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // --- initialize Firebase ---
  useEffectApp(() => {
    initFirebase();
  }, []);

  // --- viewport mode (auto vs forced mobile vs forced desktop) ---
  useEffectApp(() => {
    const root = document.documentElement;
    root.classList.remove('vp-mobile', 'vp-desktop');
    if (tweaks.viewport === 'mobile') root.classList.add('vp-mobile');
    if (tweaks.viewport === 'desktop') root.classList.add('vp-desktop');
  }, [tweaks.viewport]);

  // --- accent color application ---
  useEffectApp(() => {
    const preset = ACCENT_PRESETS[tweaks.accentName] || ACCENT_PRESETS['A7 mint'];
    const root = document.documentElement;
    root.style.setProperty('--accent', preset.c);
    root.style.setProperty('--accent-ink', preset.ink);
    // soft / glow derive from accent
    const hex = preset.c.replace('#', '');
    const r = parseInt(hex.slice(0,2), 16);
    const g = parseInt(hex.slice(2,4), 16);
    const b = parseInt(hex.slice(4,6), 16);
    root.style.setProperty('--accent-soft', `rgba(${r}, ${g}, ${b}, 0.16)`);
    root.style.setProperty('--accent-glow', `rgba(${r}, ${g}, ${b}, 0.45)`);
  }, [tweaks.accentName]);

  // --- courts (editable list) ---
  const [courts, setCourts] = useStateApp([
    { id: 'f7', name: 'Fútbol 7', type: 'F7', price: TWEAK_DEFAULTS.priceF7 },
  ]);
  // Sync prices from tweaks for known IDs
  const priceMap = useMemoApp(() => {
    const m = {};
    courts.forEach(c => { m[c.id] = c.price; });
    if (tweaks.priceF5) m.f5 = tweaks.priceF5;
    if (tweaks.priceF7) m.f7 = tweaks.priceF7;
    return m;
  }, [courts, tweaks.priceF5, tweaks.priceF7]);

  // --- active court + selection ---
  const [activeCourtId, setActiveCourtId] = useStateApp('f7');
  const [selected, setSelected] = useStateApp({ date: null, hour: null });

  // --- bookings (overlay on top of pseudo-random availability) ---
  const [bookings, setBookings] = useStateApp({});
  const [reservations, setReservations] = useStateApp([]);

  // Load bookings from Firestore when date changes
  useEffectApp(() => {
    if (!selected.date) return;
    
    async function loadBookings() {
      const firestoreBookings = await getAllBookingsForDate(selected.date);
      setBookings(prev => ({ ...prev, ...firestoreBookings }));
    }
    
    loadBookings();
  }, [selected.date]);

  // --- booking modal ---
  const [bookingOpen, setBookingOpen] = useStateApp(false);
  const [bookingPrefill, setBookingPrefill] = useStateApp(null);

  // --- mobile menu ---
  const [menuOpen, setMenuOpen] = useStateApp(false);

  // --- court editor modal ---
  const [editorOpen, setEditorOpen] = useStateApp(false);

  const toast = useToast();

  function openBooking(prefill = null) {
    setBookingPrefill(prefill || {
      courtId: activeCourtId,
      date: selected.date,
      hour: selected.hour,
    });
    setBookingOpen(true);
  }

  async function handleConfirm(data) {
    // Save to Firestore
    const result = await saveBooking({
      courtId: data.courtId,
      date: data.date,
      hour: data.hour,
      nombre: data.nombre,
      telefono: data.telefono,
      email: data.email || '',
      grabacion: data.grabacion || false,
      notas: data.notas || '',
      code: data.code,
      total: data.total,
    });
    
    if (!result.success && !result.localOnly) {
      toast('Error al guardar la reserva. Intentá de nuevo.', 'error');
      return;
    }
    
    // mark slot as booked locally
    const key = `${data.courtId}|${data.date}|${data.hour}`;
    setBookings(b => ({ ...b, [key]: 'reservado' }));
    setReservations(r => [
      { ...data, createdAt: new Date().toISOString() },
      ...r,
    ]);
    toast(`Reserva ${data.code} confirmada`);
  }

  return (
    <>
      <NavBar
        name={tweaks.name}
        onReserveClick={() => openBooking()}
        onOpenMenu={() => setMenuOpen(true)}
      />
      <MobileMenu open={menuOpen} onClose={() => setMenuOpen(false)} onReserveClick={() => openBooking()}/>

      <Hero
        name={tweaks.name}
        tagline={tweaks.tagline}
        onReserveClick={() => openBooking()}
      />

      <CalendarSection>
        <Calendar
          courts={courts}
          activeCourtId={activeCourtId}
          onCourtChange={id => { setActiveCourtId(id); setSelected({ date: null, hour: null }); }}
          selected={selected}
          onSelect={s => setSelected(s)}
          bookings={bookings}
          prices={priceMap}
          density={tweaks.density}
        />

        {/* CTA bar that appears when a slot is picked */}
        <SlotCTA
          courts={courts}
          activeCourtId={activeCourtId}
          selected={selected}
          prices={priceMap}
          onReserve={() => openBooking()}
        />

        {/* Court manager */}
        <div style={{
          marginTop: 32, padding: 20, borderRadius: 16,
          background: 'var(--surface-1)', boxShadow: 'inset 0 0 0 1px var(--hair-2)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          gap: 16, flexWrap: 'wrap',
        }}>
          <div>
            <div className="eyebrow eyebrow-muted">Admin</div>
            <div style={{ fontWeight: 800, fontSize: 17, marginTop: 4 }}>
              Gestioná tus canchas
            </div>
            <div style={{ fontSize: 13, color: 'var(--fill-tertiary)', marginTop: 2 }}>
              Agregá nuevos tipos (paddle, futsal indoor) o editá precios.
            </div>
          </div>
          <Button variant="ghost" icon="edit" onClick={() => setEditorOpen(true)}>
            Editar canchas
          </Button>
        </div>
      </CalendarSection>

      <ViviloDeNuevo onAdd={() => openBooking({ ...bookingPrefill, courtId: activeCourtId })}/>
      <Servicios/>
      <Ubicacion name={tweaks.name}/>
      <Footer name={tweaks.name}/>

      <BookingFlow
        open={bookingOpen}
        onClose={() => setBookingOpen(false)}
        onConfirm={handleConfirm}
        courts={courts}
        prices={priceMap}
        prefill={bookingPrefill}
        bookings={bookings}
      />

      <CourtEditor
        open={editorOpen}
        onClose={() => setEditorOpen(false)}
        courts={courts}
        onChange={setCourts}
      />

      <Tweaks
        tweaks={tweaks}
        setTweak={setTweak}
        courts={courts}
        onEditCourts={() => setEditorOpen(true)}
        reservations={reservations}
      />
    </>
  );
}

// ---------- Slot CTA bar (sticky-feeling) ----------
function SlotCTA({ courts, activeCourtId, selected, prices, onReserve }) {
  if (!selected.date || !selected.hour) return null;
  const court = courts.find(c => c.id === activeCourtId);
  return (
    <div className="fade-slide" style={{
      marginTop: 24, padding: 16, borderRadius: 18,
      background: 'linear-gradient(180deg, rgba(90,247,169,0.12), rgba(90,247,169,0.04))',
      boxShadow: 'inset 0 0 0 1.5px var(--accent), 0 20px 60px rgba(90,247,169,0.18)',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      gap: 16, flexWrap: 'wrap',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
        <div style={{
          width: 56, height: 56, borderRadius: 14,
          background: 'rgba(0,0,0,0.4)', boxShadow: 'inset 0 0 0 1px var(--accent)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--accent)',
        }}><Icon name="football" size={26}/></div>
        <div>
          <div style={{ fontSize: 11, fontWeight: 900, letterSpacing: '0.14em', color: 'var(--accent)' }}>
            TURNO ELEGIDO
          </div>
          <div style={{ fontWeight: 800, fontSize: 17, marginTop: 4 }}>
            {court?.name} · {window.formatDateLong(selected.date)} · {selected.hour} hs
          </div>
          <div className="num" style={{ fontSize: 13, color: 'var(--fill-secondary)', marginTop: 2 }}>
            ${(prices[activeCourtId] ?? 0).toLocaleString('es-AR')} · 60 minutos · Pago al llegar
          </div>
        </div>
      </div>
      <Button onClick={onReserve} iconAfter="arrow-right">Reservar este turno</Button>
    </div>
  );
}

// ---------- Court editor modal ----------
function CourtEditor({ open, onClose, courts, onChange }) {
  const [local, setLocal] = useStateApp(courts);
  useEffectApp(() => { if (open) setLocal(courts); }, [open]);

  function update(id, patch) {
    setLocal(l => l.map(c => c.id === id ? { ...c, ...patch } : c));
  }
  function remove(id) {
    setLocal(l => l.filter(c => c.id !== id));
  }
  function add() {
    const id = `c${Date.now().toString(36)}`;
    setLocal(l => [...l, { id, name: 'Nueva cancha', type: 'CANCHA', price: 15000 }]);
  }
  function save() {
    onChange(local);
    onClose();
  }
  return (
    <Modal open={open} onClose={onClose} maxWidth={640}>
      <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--hair-2)', display: 'flex', justifyContent: 'space-between' }}>
        <div>
          <div className="eyebrow">Admin</div>
          <div style={{ fontWeight: 800, fontSize: 22, marginTop: 6 }}>Gestionar canchas</div>
        </div>
        <button onClick={onClose} style={{
          width: 36, height: 36, borderRadius: 999, background: 'var(--surface-2)',
          boxShadow: 'inset 0 0 0 1px var(--hair-3)',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        }}><Icon name="close"/></button>
      </div>
      <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 12 }}>
        {local.map(c => (
          <div key={c.id} style={{
            display: 'grid',
            gridTemplateColumns: '70px 1fr 130px 40px',
            gap: 10, alignItems: 'center',
            padding: 12, borderRadius: 12,
            background: 'var(--surface-2)', boxShadow: 'inset 0 0 0 1px var(--hair-3)',
          }}>
            <input
              value={c.type}
              onChange={e => update(c.id, { type: e.target.value.toUpperCase() })}
              style={{
                width: '100%', padding: '8px 10px', background: 'var(--bg)',
                borderRadius: 8, fontWeight: 900, fontSize: 12, letterSpacing: '0.08em',
                textAlign: 'center', color: 'var(--accent)',
                boxShadow: 'inset 0 0 0 1px var(--hair-3)',
              }}
              maxLength={6}
            />
            <input
              value={c.name}
              onChange={e => update(c.id, { name: e.target.value })}
              style={{
                width: '100%', padding: '10px 12px', background: 'var(--bg)',
                borderRadius: 8, fontWeight: 700, fontSize: 15,
                boxShadow: 'inset 0 0 0 1px var(--hair-3)',
              }}
            />
            <div style={{ position: 'relative' }}>
              <span style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--fill-tertiary)', fontWeight: 700, fontSize: 14 }}>$</span>
              <input
                type="number"
                value={c.price}
                onChange={e => update(c.id, { price: Number(e.target.value) || 0 })}
                style={{
                  width: '100%', padding: '10px 12px 10px 22px', background: 'var(--bg)',
                  borderRadius: 8, fontWeight: 700, fontSize: 14,
                  boxShadow: 'inset 0 0 0 1px var(--hair-3)',
                }}
                className="num"
              />
            </div>
            <button onClick={() => remove(c.id)} disabled={local.length <= 1}
              style={{
                width: 40, height: 40, borderRadius: 10,
                background: 'rgba(244,63,94,0.08)',
                color: '#f87171', opacity: local.length <= 1 ? 0.3 : 1,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              }}
              aria-label="Eliminar"
            ><Icon name="trash" size={16}/></button>
          </div>
        ))}
        <button onClick={add} style={{
          padding: 14, borderRadius: 12,
          background: 'transparent',
          boxShadow: 'inset 0 0 0 1.5px var(--hair-3)',
          color: 'var(--accent)', fontWeight: 800, fontSize: 14,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}><Icon name="plus" size={16}/> Agregar cancha</button>
      </div>
      <div style={{
        padding: '16px 24px', borderTop: '1px solid var(--hair-2)',
        display: 'flex', gap: 12, justifyContent: 'flex-end',
      }}>
        <Button variant="ghost" onClick={onClose}>Cancelar</Button>
        <Button onClick={save} icon="check">Guardar</Button>
      </div>
    </Modal>
  );
}

// ---------- Tweaks panel ----------
function Tweaks({ tweaks, setTweak, courts, onEditCourts, reservations }) {
  return (
    <TweaksPanel title="Tweaks · Área 7">
      <TweakSection label="Marca">
        <TweakText
          label="Nombre"
          value={tweaks.name}
          onChange={v => setTweak('name', v)}
        />
        <TweakText
          label="Tagline"
          value={tweaks.tagline}
          onChange={v => setTweak('tagline', v)}
        />
      </TweakSection>

      <TweakSection label="Color de acento">
        <TweakSelect
          label="Preset"
          value={tweaks.accentName}
          options={Object.keys(ACCENT_PRESETS)}
          onChange={v => setTweak('accentName', v)}
        />
      </TweakSection>

      <TweakSection label="Precios">
        <TweakNumber
          label="Fútbol 5 ($/h)"
          value={tweaks.priceF5}
          step={500}
          onChange={v => setTweak('priceF5', v)}
        />
        <TweakNumber
          label="Fútbol 7 ($/h)"
          value={tweaks.priceF7}
          step={500}
          onChange={v => setTweak('priceF7', v)}
        />
        <TweakButton label={`Editar canchas (${courts.length})`} onClick={onEditCourts}/>
      </TweakSection>

      <TweakSection label="Vista">
        <TweakRadio
          label="Viewport"
          value={tweaks.viewport}
          options={['auto', 'mobile', 'desktop']}
          onChange={v => setTweak('viewport', v)}
        />
        <TweakRadio
          label="Calendario"
          value={tweaks.density}
          options={['comfortable', 'compact']}
          onChange={v => setTweak('density', v)}
        />
      </TweakSection>

      {reservations.length > 0 && (
        <TweakSection label={`Reservas (${reservations.length})`}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 200, overflow: 'auto' }}>
            {reservations.slice(0, 5).map(r => (
              <div key={r.code} style={{
                padding: 10, borderRadius: 8,
                background: 'rgba(255,255,255,0.04)',
                fontSize: 12, lineHeight: 1.4,
              }}>
                <div style={{ fontWeight: 800, color: 'var(--accent, #5af7a9)' }}>{r.code}</div>
                <div style={{ opacity: 0.7 }}>{r.nombre} · {r.date} {r.hour}</div>
              </div>
            ))}
          </div>
        </TweakSection>
      )}
    </TweaksPanel>
  );
}

// ---------- Mount with toast provider ----------
function Root() {
  return (
    <ToastProvider>
      <App/>
    </ToastProvider>
  );
}

const root = ReactDOM.createRoot(document.getElementById('app'));
root.render(<Root/>);
