/* ============================================================
   ATUKASA SUSHI — App principal (Rail layout)
   ============================================================ */
const { useState, useEffect, useRef, useMemo } = React;

const REVIEWS_DATA = [
  { name: "María A.",   rating: "★★★★★", text: "El mejor sushi de San Cristóbal, sin discusión. El crispy chicken lo pedimos cada vez que vamos.", time: "Hace 2 sem." },
  { name: "Carlos M.",  rating: "★★★★★", text: "Nunca pensé encontrar sushi así aquí. El tempura roll con queso Philadelphia te cambia la vida.", time: "Hace 1 mes" },
  { name: "Ana L.",     rating: "★★★★★", text: "Lo mejor que tiene San Cristóbal. Los dumplings son perfectos. Volvemos siempre.", time: "Hace 3 sem." },
  { name: "Lucia P.",   rating: "★★★★★", text: "Primera vez comiendo sushi y ahora soy adicta. El crispy con plátano maduro es increíble.", time: "Hace 1 mes" },
  { name: "Roberto F.", rating: "★★★★★", text: "He comido en la capital y el de Atukasa está igual de bueno. Calidad real en San Cristóbal.", time: "Hace 2 m." },
  { name: "Diana V.",   rating: "★★★★★", text: "El delivery siempre a tiempo y el sushi en perfectas condiciones. Muy recomendado.", time: "Hace 1 sem." },
];

function ReviewsTicker() {
  const all = [...REVIEWS_DATA, ...REVIEWS_DATA];
  return (
    <div className="p2reviews" style={{height:'180px',borderRadius:'10px',flex:'1 1 auto'}}>
      <div className="p2reviews__track">
        {all.map((r, i) => (
          <div key={i} className="p2review">
            <div className="p2review__top">
              <div className="p2review__av">{r.name.charAt(0)}</div>
              <div className="p2review__info">
                <div className="p2review__name">{r.name}</div>
                <div className="p2review__stars">{r.rating}</div>
              </div>
              <span className="p2review__time">{r.time}</span>
            </div>
            <p className="p2review__text">{r.text}</p>
          </div>
        ))}
      </div>
    </div>
  );
}

function App() {
  const { CATEGORIES, PRODUCTS, BUSINESS } = window.ATUKASA;
  const [active, setActive]       = useState(CATEGORIES[0].id);
  const [modal, setModal]         = useState(null);
  const [cartOpen, setCartOpen]   = useState(false);
  const [loyaltyOpen, setLoyaltyOpen] = useState(false);
  const { user, login }           = useLoyalty();
  const [items, setItems]         = useState(() => {
    try { return JSON.parse(localStorage.getItem("atukasa_cart") || "[]"); }
    catch (e) { return []; }
  });
  const [toast, setToast] = useState(null);

  const scrollRef   = useRef(null);
  const sectionRefs = useRef({});
  const lockSpy     = useRef(false);

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

  const countByCat = useMemo(() => {
    const m = {};
    PRODUCTS.forEach((p) => { m[p.cat] = (m[p.cat] || 0) + 1; });
    return m;
  }, []);

  const cartCount = items.reduce((s, it) => s + it.qty, 0);
  const cartTotal = items.reduce((s, it) => s + it.unit * it.qty, 0);

  const goToCat = (id) => {
    setActive(id);
    const cont = scrollRef.current;
    if (!cont) return;
    lockSpy.current = true;
    if (id === "promos") {
      cont.scrollTo({ top: cont.scrollHeight, behavior: "smooth" });
    } else {
      const el = sectionRefs.current[id];
      if (el) cont.scrollTo({ top: el.offsetTop - 8, behavior: "smooth" });
    }
    setTimeout(() => { lockSpy.current = false; }, 600);
  };

  const onScroll = () => {
    if (lockSpy.current) return;
    const cont = scrollRef.current;
    const top  = cont.scrollTop + 80;
    let current = CATEGORIES[0].id;
    for (const c of CATEGORIES) {
      const el = sectionRefs.current[c.id];
      if (el && el.offsetTop <= top) current = c.id;
    }
    setActive((a) => (a === current ? a : current));
  };

  const addItem = (item) => {
    setItems((cur) => {
      const found = cur.find((x) => x.key === item.key);
      if (found) return cur.map((x) => x.key === item.key ? { ...x, qty: x.qty + item.qty } : x);
      return [...cur, item];
    });
    setToast(item.name + " agregado");
    setTimeout(() => setToast(null), 1800);
  };
  const setQty     = (key, q) => setItems((cur) => cur.map((x)  => x.key === key ? { ...x, qty: q } : x));
  const removeItem = (key)    => setItems((cur) => cur.filter((x) => x.key !== key));
  const clearCart  = ()       => setItems([]);

  const now    = new Date();
  const isOpen = BUSINESS.openDays.includes(now.getDay()) &&
    now.getHours() >= BUSINESS.openFrom && now.getHours() < BUSINESS.openTo;

  const mapsUrl = "https://google.com/maps/place/AtuKasa+Sushi/data=!4m2!3m1!1s0x0:0xaed0104586fa4d07?sa=X&ved=1t:2428&ictx=111";

  return (
    <div className="app">

      {/* ── HEADER ── */}
      <header className="topbar">
        <a className="brand" href="Atukasa Sushi.html">
          <img className="brand__badge" src="/wp-content/uploads/atukasa/Isotipo atukasa sushi 2026.png" alt="Atukasa Sushi" />
          <span className="brand__txt">
            <span className="brand__word">ATUKASA</span>
            <span className="brand__sub">SUSHI</span>
          </span>
        </a>
        <div className="topbar__loc">
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none">
            <path d="M12 21s7-5.7 7-11a7 7 0 10-14 0c0 5.3 7 11 7 11z" stroke="currentColor" strokeWidth="1.8"/>
            <circle cx="12" cy="10" r="2.4" stroke="currentColor" strokeWidth="1.8"/>
          </svg>
          <span>San Cristóbal</span>
          <em className={"dot " + (isOpen ? "dot--open" : "dot--closed")} />
          <span className={isOpen ? "topbar__open" : "topbar__closed"}>{isOpen ? "Abierto ahora" : "Cerrado"}</span>
        </div>
        <div className="topbar__spacer" />
        <LoyaltyChip user={user} onOpen={() => setLoyaltyOpen(true)} />
        <AccountChip memberUser={user} onOpenLoyalty={() => setLoyaltyOpen(true)} />
        <SiteMenu active="menu" />
        <button className="cartbtn" onClick={() => setCartOpen(true)}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
            <path d="M5 7h14l-1.2 10.2A2 2 0 0115.8 19H8.2a2 2 0 01-2-1.8L5 7z" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round"/>
            <path d="M9 7a3 3 0 016 0" stroke="currentColor" strokeWidth="1.8"/>
          </svg>
          {cartCount > 0 && <span className="cartbtn__badge">{cartCount}</span>}
        </button>
      </header>

      {/* ── LAYOUT ── */}
      <div className="layout">
        <CategoryRail cats={CATEGORIES} active={active} onPick={goToCat} countByCat={countByCat} />

        <main className="content" ref={scrollRef} onScroll={onScroll}>

          {/* HERO */}
          <div className="hero">
            <div className="hero__enso">
              <img src="/wp-content/uploads/atukasa/Circulo Rojo Atukasa Sushi Nueva imagen.webp" alt="" className="hero__enso-img" />
              <img src="/wp-content/uploads/atukasa/tempura multi toppin  banner principal 1.webp" alt="" className="hero__enso-food" />
            </div>
            <img className="hero__badge" src="/wp-content/uploads/atukasa/Logo Atukasa Sushi 2026 con textura Para fondo nego.webp" alt="" />
            <div className="hero__txt">
              <div className="hero__kicker">The <b>Dominikkei</b> Experience</div>
              <h1 className="hero__title">El sabor de</h1>
              <div className="hero__script">sentirse bien.</div>
              <p className="hero__sub">La fusión perfecta entre Japón y República Dominicana. <b>Pide en segundos</b> desde tu celular: elige porciones, agrega toppings y ordena por WhatsApp.</p>
            </div>
          </div>

          {/* SECCIONES */}
          {CATEGORIES.map((c) => {
            const prods = PRODUCTS.filter((p) => p.cat === c.id);
            return (
              <section key={c.id} className="catsec" ref={(el) => (sectionRefs.current[c.id] = el)}>
                <div className="catsec__head">
                  <div>
                    <h2 className="catsec__title">{c.name}</h2>
                    <p className="catsec__note">{c.note}</p>
                  </div>
                  {prods.length > 0 && (
                    <span className="catsec__count">{prods.length} {prods.length === 1 ? "plato" : "platos"}</span>
                  )}
                </div>
                <div className="grid">
                  {prods.length === 0 && c.id === "promos" ? (
                    <div className="promobanner">
                      <img className="promobanner__bg" src="/wp-content/uploads/atukasa/ChatGPT Image 7 jun 2026, 21_01_52.webp" alt="" />
                      <div className="promobanner__overlay" />
                      <div className="promobanner__copy">
                        <div className="promobanner__kicker">Los miércoles son de todos</div>
                        <h2 className="promobanner__title">Empanizados</h2>
                        <span className="promobanner__script">gratis.</span>
                      </div>
                    </div>
                  ) : prods.length === 0 ? (
                    <div className="emptycat">
                      <div className="emptycat__mark">%</div>
                      <h3>Próximamente</h3>
                      <p>Estamos cocinando nuevas promociones para ti. Vuelve pronto o escríbenos por WhatsApp para conocer las ofertas del día.</p>
                    </div>
                  ) : prods.map((p) => (
                    <ProductCard key={p.id} product={p} onOpen={setModal} />
                  ))}
                </div>
              </section>
            );
          })}

          {/* FOOTER */}
          <footer className="sucursales">
            <h3>Visítanos</h3>
            <div className="sucursales__grid">

              {/* Dirección + GPS */}
              <div className="sucard">
                <span className={"dot " + (isOpen ? "dot--open" : "dot--closed")} style={{flexShrink:0}} />
                <div style={{display:'flex',flexDirection:'column',gap:'3px'}}>
                  <strong>{BUSINESS.address}</strong>
                  <span>{BUSINESS.hoursLabel} · {isOpen ? "Abierto ahora" : "Cerrado"}</span>
                  <a href={mapsUrl} target="_blank" className="sucard__gps">
                    <svg width="11" height="11" viewBox="0 0 24 24" fill="none">
                      <path d="M12 21s-7-5.7-7-11a7 7 0 1114 0c0 5.3-7 11-7 11z" stroke="currentColor" strokeWidth="1.8"/>
                      <circle cx="12" cy="10" r="2.4" stroke="currentColor" strokeWidth="1.8"/>
                    </svg>
                    18°25'N, 70°06'O · Ver en Google Maps
                  </a>
                </div>
              </div>

              {/* Reseñas Google (reemplaza Delivery) */}
              <div className="sucard sucard--reviews">
                <div className="sucard__rev-head">
                  <span className="sucard__rev-label">Lo que dice la gente</span>
                  <a href="https://google.com/maps/place/AtuKasa+Sushi/data=!4m2!3m1!1s0x0:0xaed0104586fa4d07?sa=X&ved=1t:2428&ictx=111" target="_blank" className="sucard__rev-link">
                    Ver en Google Maps →
                  </a>
                </div>
                <ReviewsTicker />
              </div>

              {/* Redes */}
              <div className="sucard">
                <span className="dot dot--open" style={{flexShrink:0}} />
                <div>
                  <strong>{BUSINESS.ig}</strong>
                  <span>Instagram · Facebook · TikTok</span>
                </div>
              </div>

            </div>
            <p className="sucursales__legal">{BUSINESS.web} · Precios en RD$ con ITBIS incluido. Imágenes de referencia, reemplazables por fotos reales.</p>
          </footer>

        </main>
      </div>

      {/* BARRA MÓVIL */}
      {cartCount > 0 && (
        <button className="mobilebar" onClick={() => setCartOpen(true)}>
          <span className="mobilebar__count">{cartCount}</span>
          <span className="mobilebar__label">Ver pedido</span>
          <span className="mobilebar__total">RD$ {fmt(cartTotal)}</span>
        </button>
      )}


      {/* LOYALTY MODAL */}
      {loyaltyOpen && <LoyaltyModal onClose={() => setLoyaltyOpen(false)} member={user} />}

      {/* MODAL */}
      {modal && <ProductModal product={modal} onClose={() => setModal(null)} onAdd={addItem} />}

      {/* DRAWER */}
      <CartDrawer
        open={cartOpen}
        items={items}
        onClose={() => setCartOpen(false)}
        onQty={setQty}
        onRemove={removeItem}
        onClear={clearCart}
        user={user}
        onOpenLoyalty={() => setLoyaltyOpen(true)}
      />

      {/* TOAST */}
      {toast && (
        <div className="toast">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
            <path d="M5 13l4 4L19 7" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          {toast}
        </div>
      )}
    </div>
  );
}

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