/* ─────────────────────────────────────────────────
   Furnishfy — Home page  (English, LTR)
   Sections:
     1. Hero Banner
     2. Categories Slider (circular, named)
     3. Best Sellers slider
     4. Per-Category product rows
   ───────────────────────────────────────────────── */

/* ── ProductCardSlide ── */
function ProductCardSlide({ p, go }) {
  const hasImg = p.thumbnail && !p.thumbnail.includes('no-product');
  return (
    <div
      className="pcard-slide"
      onClick={() => go('product', p.id)}
      style={{ cursor: 'pointer', flexShrink: 0, width: 220 }}
    >
      <div className="pcard-slide-img">
        {hasImg
          ? <img src={p.thumbnail} alt={p.en} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
          : <Placeholder hue={p.hue} label={p.cat} style={{ position: 'absolute', inset: 0 }} />
        }
        {p.badge && <span className="pcard-badge">{p.badge.en}</span>}
        <div className="pcard-hover">
          <button className="btn btn--solid" style={{ width: '100%', padding: '11px 16px', fontSize: 13 }}>
            <span>View piece</span>
          </button>
        </div>
      </div>
      <div style={{ paddingTop: 12 }}>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 16, lineHeight: 1.2, color: 'var(--ink)' }}>
          {p.en}
        </div>
        <div style={{ marginTop: 6, display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
          <span style={{ color: 'var(--gold)', fontFamily: 'var(--font-display)', fontSize: 15 }}>
            {money(p.price)}
          </span>
          {p.old && (
            <span style={{ color: 'var(--faint)', fontSize: 12.5, textDecoration: 'line-through' }}>
              {money(p.old)}
            </span>
          )}
        </div>
      </div>
    </div>
  );
}

/* ── CategorySlider ── */
function CategorySlider({ categories, go, lang }) {
  const trackRef = useRef(null);
  const [canPrev, setCanPrev] = useState(false);
  const [canNext, setCanNext] = useState(true);

  const ITEM_W = 130; // approx width of each item + gap

  const scroll = (dir) => {
    if (!trackRef.current) return;
    trackRef.current.scrollBy({ left: dir * ITEM_W * 2, behavior: 'smooth' });
  };

  useEffect(() => {
    const el = trackRef.current;
    if (!el) return;
    const update = () => {
      setCanPrev(el.scrollLeft > 4);
      setCanNext(el.scrollLeft + el.clientWidth < el.scrollWidth - 4);
    };
    el.addEventListener('scroll', update, { passive: true });
    update();
    return () => el.removeEventListener('scroll', update);
  }, []);

  const hues = [28, 95, 55, 75, 18, 40, 65, 85, 50, 30, 60, 20];

  return (
    <div className="cat-slider-wrap">
      {canPrev && (
        <button
          onClick={() => scroll(-1)}
          className="slider-arrow slider-arrow--prev"
          aria-label="Previous"
        >
          <Icon name="arrowL" size={18} />
        </button>
      )}
      {canNext && (
        <button
          onClick={() => scroll(1)}
          className="slider-arrow slider-arrow--next"
          aria-label="Next"
        >
          <Icon name="arrow" size={18} />
        </button>
      )}

      {/* scrollable track */}
      <div
        ref={trackRef}
        style={{
          display: 'flex',
          gap: 24,
          overflowX: 'auto',
          scrollBehavior: 'smooth',
          scrollbarWidth: 'none',
          padding: '8px 4px 48px',
          msOverflowStyle: 'none',
        }}
      >
        {categories.map((c, i) => (
          <div
            key={c.id}
            onClick={() => go('shop', null, c.id)}
            className="cat-item"
          >
            {/* circle */}
            <div className="cat-circle">
              {c.image
                ? <img
                  src={c.image.startsWith('http') ? c.image : `/uploads/categories/${c.image}`}
                  alt={c.en}
                />
                : <Placeholder
                  hue={hues[i % hues.length]}
                  label=""
                  style={{ position: 'absolute', inset: 0, borderRadius: '50%' }}
                />
              }
            </div>
            {/* name — always visible below the circle */}
            <span className="cat-item-name">{lang === "ar" ? c.ar : c.en}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ── CategoryProductRow ── */
function CategoryProductRow({ section, go, lang }) {
  const CARD_W = 220;
  const GAP = 20;
  const VIS = 4;
  const [offset, setOffset] = useState(0);
  const maxOff = Math.max(0, section.products.length - VIS);

  return (
    <div className="reveal" style={{ marginBottom: 72 }}>
      {/* row header */}
      <div style={{
        display: 'flex', alignItems: 'center',
        justifyContent: 'space-between',
        marginBottom: 24, flexWrap: 'wrap', gap: 12,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ display: 'flex', gap: 8 }}>
            <button
              onClick={() => setOffset(o => Math.max(0, o - 1))}
              disabled={offset === 0}
              className="cat-arrow-btn"
              aria-label="Previous"
            >
              <Icon name="arrowL" size={15} />
            </button>
            <button
              onClick={() => setOffset(o => Math.min(maxOff, o + 1))}
              disabled={offset >= maxOff}
              className="cat-arrow-btn"
              aria-label="Next"
            >
              <Icon name="arrow" size={15} />
            </button>
          </div>
          <h2 style={{
            fontSize: 'clamp(20px,2.2vw,28px)',
            fontFamily: 'var(--font-display)',
            color: 'var(--ink)', margin: 0,
          }}>
            {lang === "ar" ? section.ar : section.en}
          </h2>
        </div>
        <button
          onClick={() => go('shop', null, section.id)}
          className="btn btn--ghost"
          style={{ fontSize: 12, padding: '10px 22px' }}
        >
          <span>View all</span>
        </button>
      </div>

      {/* slider */}
      <div className="product-slider-container">
        <div className="product-slider-track" style={{
          display: 'flex',
          gap: GAP + 'px',
          transition: 'transform 0.45s cubic-bezier(0.22,1,0.36,1)',
          transform: `translateX(${-offset * (CARD_W + GAP)}px)`,
        }}>
          {section.products.map((p) => (
            <ProductCardSlide key={p.id} p={p} go={go} />
          ))}
        </div>
      </div>
    </div>
  );
}

/* ══════════════════════════════════════════════════
   Main Home Component
══════════════════════════════════════════════════ */
function Home({ go, lang }) {
  useReveal();

  const {
    PRODUCTS, CATEGORIES, BANNERS,
    BEST_SELLERS, PRODUCTS_BY_CATEGORY,
  } = window.FURN;

  /* Best sellers fallback */
  const bestSellers = (BEST_SELLERS && BEST_SELLERS.length > 0)
    ? BEST_SELLERS
    : PRODUCTS.slice(0, 8);

  /* Per-category fallback */
  const productsByCategory = (PRODUCTS_BY_CATEGORY && PRODUCTS_BY_CATEGORY.length > 0)
    ? PRODUCTS_BY_CATEGORY
    : CATEGORIES.filter(c => !c.parent).map(c => ({
      id: c.id, en: c.en, ar: c.ar,
      products: PRODUCTS.filter(p => p.cat === c.id || CATEGORIES.find(sub => sub.id === p.cat)?.parent === c.id),
    })).filter(g => g.products.length > 0);

  /* ── Hero banner ── */
  const bannersToUse = (BANNERS && BANNERS.length > 0) ? BANNERS : [
    {
      title_en: 'The 2026 Collection',
      subtitle_en: 'Furniture that outlives the trend.',
      image: '', link: '#',
    },
  ];
  const [slide, setSlide] = useState(0);
  useEffect(() => {
    if (bannersToUse.length <= 1) return;
    const t = setInterval(() => setSlide(s => (s + 1) % bannersToUse.length), 5000);
    return () => clearInterval(t);
  }, [bannersToUse.length]);
  const activeBanner = bannersToUse[slide];

  /* ── Best sellers slider offset ── */
  const BS_W = 220;
  const BS_GAP = 20;
  const BS_VIS = 4;
  const [bsOff, setBsOff] = useState(0);
  const bsMax = Math.max(0, bestSellers.length - BS_VIS);

  return (
    <main className="page-fade">

      {/* ══ 1. HERO BANNER ══ */}
      <section style={{
        position: 'relative', minHeight: '100vh',
        display: 'flex', alignItems: 'flex-end',
        overflow: 'hidden',
      }}>
        {bannersToUse.map((banner, i) => (
          <div key={i} style={{
            position: 'absolute', inset: 0,
            opacity: slide === i ? 1 : 0,
            transition: 'opacity 1.2s ease-in-out',
            background: banner.image && !banner.image.endsWith('null')
              ? `url(${banner.image}) no-repeat center/cover`
              : 'none',
            zIndex: 0,
          }}>
            {(!banner.image || banner.image.endsWith('null')) && (
              <Placeholder hue={28 + i * 45} label="" style={{ position: 'absolute', inset: 0 }} />
            )}
          </div>
        ))}

        {/* gradient overlay */}
        <div style={{
          position: 'absolute', inset: 0, zIndex: 1,
          background: 'linear-gradient(to top, var(--bg) 4%, transparent 55%), linear-gradient(to right, color-mix(in oklch, var(--bg-deep) 80%, transparent), transparent 60%)',
        }} />

        {/* copy */}
        <div className="wrap" style={{ position: 'relative', zIndex: 2, paddingBottom: 88, width: '100%' }}>
          <div className="reveal in" style={{ maxWidth: 720 }}>
            <div className="eyebrow">The 2026 Collection — Limited Release</div>
            <h1 style={{ fontSize: 'clamp(42px,7vw,92px)', margin: '22px 0 0', letterSpacing: '-0.01em' }}>
              {activeBanner.title_en}
            </h1>
            <p style={{ color: 'var(--muted)', fontSize: 'clamp(15px,1.5vw,18px)', maxWidth: 480, marginTop: 26, lineHeight: 1.75 }}>
              {activeBanner.subtitle_en}
            </p>
            <div style={{ display: 'flex', gap: 16, marginTop: 38, flexWrap: 'wrap' }}>
              <button className="btn btn--solid" onClick={() => go('shop')}>
                <span>Explore collection <Icon name="arrow" size={16} /></span>
              </button>
              <button className="btn" onClick={() => go('rooms')}>
                <span>Shop by room</span>
              </button>
            </div>
          </div>
        </div>

        {/* dots */}
        {bannersToUse.length > 1 && (
          <div style={{
            position: 'absolute', bottom: 30, left: '50%',
            transform: 'translateX(-50%)', zIndex: 3,
            display: 'flex', gap: 8,
          }}>
            {bannersToUse.map((_, i) => (
              <button key={i} onClick={() => setSlide(i)} style={{
                width: 8, height: 8, borderRadius: '50%',
                border: 'none', cursor: 'pointer',
                background: slide === i ? 'var(--gold)' : 'oklch(1 0 0 / 0.3)',
                transition: 'background .3s',
              }} />
            ))}
          </div>
        )}

        <div className="scroll-cue" style={{
          position: 'absolute', bottom: 30, right: 44, zIndex: 2,
          display: 'flex', flexDirection: 'column', alignItems: 'center',
          gap: 10, color: 'var(--faint)',
        }}>
          <span style={{ writingMode: 'vertical-rl', fontSize: 10, letterSpacing: '.3em', textTransform: 'uppercase' }}>Scroll</span>
          <span style={{ width: 1, height: 50, background: 'linear-gradient(var(--gold), transparent)' }} />
        </div>
      </section>

      {/* ══ 2. CATEGORIES SLIDER ══ */}
      <section className="wrap" style={{ padding: '80px 40px 60px' }}>
        <div className="reveal" style={{ marginBottom: 40 }}>
          <div className="eyebrow">Shop by category</div>
          <h2 style={{ fontSize: 'clamp(28px,4vw,48px)', marginTop: 14 }}>Featured Categories</h2>
        </div>
        <div className="reveal in">
          <CategorySlider categories={CATEGORIES.filter(c => !c.parent).filter(c => {
            const childIds = CATEGORIES.filter(sub => sub.parent === c.id).map(sub => sub.id);
            const count = PRODUCTS.filter(p => p.cat === c.id || childIds.includes(p.cat)).length;
            return count > 0;
          })} go={go} lang={lang} />
        </div>
      </section>


      {/* ══ 3. BEST SELLERS ══ */}
      <section style={{
        background: 'var(--bg-deep)',
        borderTop: '1px solid var(--line)',
        borderBottom: '1px solid var(--line)',
        padding: '70px 0',
      }}>
        <div className="wrap" style={{ padding: '0 40px' }}>
          <div className="reveal" style={{
            display: 'flex', alignItems: 'flex-end',
            justifyContent: 'space-between',
            marginBottom: 36, flexWrap: 'wrap', gap: 12,
          }}>
            <div>
              <div className="eyebrow">Top picks</div>
              <h2 style={{ fontSize: 'clamp(28px,4vw,48px)', marginTop: 14 }}>Best Sellers</h2>
            </div>
            <button onClick={() => go('shop')} className="btn" style={{ fontSize: 12 }}>
              <span>View all</span>
            </button>
          </div>

          <div className="reveal" style={{ position: 'relative' }}>
            {bsOff > 0 && (
              <button
                onClick={() => setBsOff(o => Math.max(0, o - 1))}
                className="slider-arrow slider-arrow--prev"
                aria-label="Previous"
              >
                <Icon name="arrowL" size={20} />
              </button>
            )}
            {bsOff < bsMax && (
              <button
                onClick={() => setBsOff(o => Math.min(bsMax, o + 1))}
                className="slider-arrow slider-arrow--next"
                aria-label="Next"
              >
                <Icon name="arrow" size={20} />
              </button>
            )}
            <div className="product-slider-container">
              <div className="product-slider-track" style={{
                display: 'flex',
                gap: BS_GAP + 'px',
                transition: 'transform 0.45s cubic-bezier(0.22,1,0.36,1)',
                transform: `translateX(${-bsOff * (BS_W + BS_GAP)}px)`,
              }}>
                {bestSellers.map((p) => (
                  <ProductCardSlide key={p.id} p={p} go={go} />
                ))}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* ══ 4. PRODUCTS BY CATEGORY ══ */}
      <section className="wrap" style={{ padding: '80px 40px 40px' }}>
        <div className="reveal" style={{ marginBottom: 52 }}>
          <div className="eyebrow">Browse the collection</div>
          <h2 style={{ fontSize: 'clamp(28px,4vw,48px)', marginTop: 14 }}>Shop by Category</h2>
        </div>
        {productsByCategory.map((section) => (
          <CategoryProductRow key={section.id} section={section} go={go} lang={lang} />
        ))}
      </section>

      {/* ══ STYLES ══ */}
      <style>{`
        /* ── Category Slider ── */
        .cat-slider-wrap {
          position: relative;
        }
        .cat-slider-track {
          display: flex;
          gap: 24px;
          overflow-x: auto;
          scroll-behavior: smooth;
          scrollbar-width: none;
          padding: 8px 4px 16px;
          -ms-overflow-style: none;
        }
        .cat-slider-track::-webkit-scrollbar { display: none; }

        .cat-item {
          flex-shrink: 0;
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 12px;
          background: none;
          border: none;
          cursor: pointer;
          width: 110px;
          padding: 0;
        }
        .cat-item:hover .cat-circle {
          border-color: var(--gold);
          transform: translateY(-4px);
          box-shadow: 0 8px 24px oklch(0.75 0.12 70 / 0.2);
        }
        .cat-item-name {
          font-size: 12.5px;
          color: var(--muted);
          text-align: center;
          font-family: var(--font-ui);
          font-weight: 400;
          line-height: 1.35;
          letter-spacing: 0.03em;
          display: block;
          width: 110px;
          white-space: normal;
          word-break: break-word;
          transition: color 0.25s;
          margin-top: 4px;
        }
        .cat-item:hover .cat-item-name { color: var(--ink); }

        .cat-circle {
          width: 100px;
          height: 100px;
          border-radius: 50%;
          overflow: hidden;
          position: relative;
          border: 2px solid var(--line);
          transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
          background: var(--surface);
          flex-shrink: 0;
        }

        .cat-circle img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          border-radius: 50%;
          transform: scale(1.45);
          transition: transform 0.4s cubic-bezier(0.16, 1, 0.3, 1);
        }

        .cat-item:hover .cat-circle img {
          transform: scale(1.55);
        }

        /* ── Product slide card ── */
        .pcard-slide-img {
          position: relative;
          aspect-ratio: 5/5;
          overflow: hidden;
          border-radius: var(--radius);
          border: 1px solid var(--line);
          background: var(--surface);
        }
        .pcard-slide:hover .pcard-slide-img {
          box-shadow: 0 8px 30px oklch(0 0 0 / 0.3);
        }
        .pcard-slide .pcard-hover {
          position: absolute;
          left: 10px; right: 10px; bottom: 10px;
          z-index: 3;
          transform: translateY(12px);
          opacity: 0;
          transition: all 0.4s var(--ease);
        }
        .pcard-slide:hover .pcard-hover { transform: none; opacity: 1; }
        @media (hover: none) {
          .pcard-slide .pcard-hover { transform: none; opacity: 1; }
        }

        /* ── Slider nav arrows ── */
        .slider-arrow {
          position: absolute;
          top: 38%;
          transform: translateY(-50%);
          z-index: 10;
          background: var(--surface);
          border: 1px solid var(--line);
          color: var(--ink);
          width: 40px; height: 40px;
          border-radius: 50%;
          display: flex; align-items: center; justify-content: center;
          cursor: pointer;
          transition: all 0.25s;
          box-shadow: 0 4px 16px oklch(0 0 0 / 0.25);
        }
        .slider-arrow:hover { background: var(--gold); color: var(--bg-deep); border-color: var(--gold); }
        .slider-arrow--prev { left: -20px; }
        .slider-arrow--next { right: -20px; }

        /* ── Category row arrows ── */
        .cat-arrow-btn {
          width: 32px; height: 32px;
          border-radius: 50%;
          border: 1px solid var(--line);
          background: var(--surface);
          color: var(--ink);
          display: flex; align-items: center; justify-content: center;
          cursor: pointer;
          transition: all 0.25s;
          flex-shrink: 0;
        }
        .cat-arrow-btn:hover:not(:disabled) { background: var(--gold); color: var(--bg-deep); border-color: var(--gold); }
        .cat-arrow-btn:disabled { opacity: 0.3; cursor: default; }

        .product-slider-container {
          overflow: hidden;
        }
        .product-slider-track {
          display: flex;
        }

        @media (max-width: 860px) {
          .slider-arrow, .cat-arrow-btn {
            display: none !important;
          }
          .product-slider-container {
            overflow-x: auto !important;
            scrollbar-width: none;
            -ms-overflow-style: none;
            padding-bottom: 12px;
          }
          .product-slider-container::-webkit-scrollbar {
            display: none;
          }
          .product-slider-track {
            transform: none !important;
          }
        }
        @media (max-width: 768px) {
          .slider-arrow--prev { left: -10px; }
          .slider-arrow--next { right: -10px; }
        }
        @media (max-width: 560px) {
          .cat-circle { width: 78px; height: 78px; }
          .cat-item   { width: 88px; }
          .cat-item-name { width: 88px; font-size: 11px; }
        }
      `}</style>
    </main>
  );
}

Object.assign(window, { Home });
