/* Home page */

const HERO_SLIDES = [
  { img: "img/hero.jpg", space: "bath", look: "marble" },
  { img: "img/living-2.jpg", space: "living", look: "marble" },
  { img: "img/kitchen-1.jpg", space: "kitchen", look: "concrete" },
  { img: "img/outdoor-1.jpg", space: "outdoor", look: "stone" }
];
const HERO_INTERVAL = 6500;

function HeroSlider() {
  const { t, route } = useApp();
  const n = HERO_SLIDES.length;
  const [i, setI] = useState(0);
  const [paused, setPaused] = useState(false);   // user pressed pause
  const [hover, setHover] = useState(false);     // hover / focus inside
  const reduce = useMemo(() => window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches, []);
  const [tick, setTick] = useState(0);           // restarts progress bar
  const touch = useRef(null);
  const running = !paused && !hover && !reduce;

  const goTo = k => { setI(((k % n) + n) % n); setTick(x => x + 1); };
  useEffect(() => {
    if (!running) return;
    const id = setTimeout(() => goTo(i + 1), HERO_INTERVAL);
    return () => clearTimeout(id);
  }, [i, running, tick]);
  // preload next image
  useEffect(() => { const im = new Image(); im.src = HERO_SLIDES[(i + 1) % n].img; }, [i]);

  const s = HERO_SLIDES[i];
  return (
    <div className="hero-media hs" role="region" aria-roledescription="carousel" aria-label={t("hs.label")}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      onFocus={() => setHover(true)} onBlur={e => { if (!e.currentTarget.contains(e.relatedTarget)) setHover(false); }}
      onKeyDown={e => { if (e.key === "ArrowRight") goTo(i + 1); if (e.key === "ArrowLeft") goTo(i - 1); }}
      onTouchStart={e => (touch.current = e.touches[0].clientX)}
      onTouchEnd={e => { if (touch.current == null) return; const dx = e.changedTouches[0].clientX - touch.current; if (Math.abs(dx) > 40) goTo(dx < 0 ? i + 1 : i - 1); touch.current = null; }}>
      {HERO_SLIDES.map((sl, k) => (
        <div key={sl.img} className={"hs-slide" + (k === i ? " on" : "")} role="group" aria-roledescription="slide"
          aria-label={`${k + 1} / ${n}: ${t("space." + sl.space)}`} aria-hidden={k !== i}>
          <img src={sl.img} alt={`${t("space." + sl.space)} — ${t("v." + sl.look)}`}
            loading={k === 0 ? "eager" : "lazy"} fetchpriority={k === 0 ? "high" : "low"} />
        </div>
      ))}
      <div className="hs-bar">
        <a className="hs-label" href={hrefFor(route.lang, "inspiration", null, "space=" + s.space)} aria-live={running ? "off" : "polite"}>
          <span className="hs-num">0{i + 1}<i>/0{n}</i></span>
          <span className="hs-txt"><b>{t("space." + s.space)}</b><span>{t("v." + s.look)}</span></span>
          {Ico.arrow(16)}
        </a>
        <div className="hs-ctrl">
          <button type="button" onClick={() => goTo(i - 1)} aria-label={t("g.prev")}>{Ico.left()}</button>
          <button type="button" onClick={() => goTo(i + 1)} aria-label={t("g.next")}>{Ico.right()}</button>
          {!reduce && (
            <button type="button" onClick={() => setPaused(p => !p)} aria-label={paused ? t("hs.play") : t("hs.pause")} aria-pressed={paused}>
              {paused
                ? <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 5l11 7-11 7z"/></svg>
                : <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><rect x="6" y="5" width="4" height="14"/><rect x="14" y="5" width="4" height="14"/></svg>}
            </button>
          )}
        </div>
      </div>
      <div className="hs-dots" role="tablist" aria-label={t("hs.label")}>
        {HERO_SLIDES.map((sl, k) => (
          <button key={sl.img} role="tab" aria-selected={k === i} aria-label={`${k + 1}: ${t("space." + sl.space)}`} onClick={() => goTo(k)}>
            <span className="hs-track"><span key={k === i ? "p" + tick + (running ? "r" : "s") : "x"} className={"hs-fill" + (k === i ? (running ? " run" : " full") : k < i ? " full" : "")} style={{ animationDuration: HERO_INTERVAL + "ms" }} /></span>
          </button>
        ))}
      </div>
      <span className="caption hs-cap">{t("hero.caption")}</span>
    </div>
  );
}

function Hero() {
  const { t, route } = useApp();
  return (
    <section className="hero" aria-labelledby="hero-h">
      <div className="hero-copy">
        <div>
          <p className="hero-loc"><i></i>{t("hero.loc")}</p>
          <h1 id="hero-h" className="h-display hero-title" lang={route.lang}
            style={{ "--hw": Math.max(9, ...t("hero.title").split(/\s+/).map(w => w.replace(/[.,!?]/g, "").length)) }}>{t("hero.title")}</h1>
          <p className="lead">{t("hero.sub")}</p>
          <div className="hero-ctas">
            <a className="btn btn-primary" href={hrefFor(route.lang, "products")}>{t("hero.cta1")} {Ico.arrow()}</a>
            <a className="btn btn-ghost" href={hrefFor(route.lang, "quote")}>{t("hero.cta2")}</a>
          </div>
        </div>
        <div className="hero-foot">
          {window.CATEGORIES.map(c => (
            <a key={c.id} href={hrefFor(route.lang, "category", c.id)}>{window.SEO_CONTENT[route.lang].cats[c.id].h1}</a>
          ))}
        </div>
      </div>
      <HeroSlider />
    </section>
  );
}

function Categories() {
  const { t, route } = useApp();
  const count = id => window.PRODUCTS.filter(p => p.cat === id).length;
  const CatCard = ({ c }) => (
    <a className="cat" href={hrefFor(route.lang, "category", c.id)}>
      <div className="cat-img"><img src={c.img} alt="" loading="lazy" /></div>
      <div className="cat-body">
        <h3>{window.SEO_CONTENT[route.lang].cats[c.id].h1}</h3>
        <span className="arrow">{Ico.arrow()}</span>
        <p>{t("cat." + c.id + ".d")}</p>
        <span className="cat-count">{t("cats.count", { n: count(c.id) })}</span>
      </div>
    </a>
  );
  const [a, b, c] = window.CATEGORIES;
  return (
    <section className="sec" aria-labelledby="cats-h">
      <div className="wrap">
        <div className="sec-head">
          <div>
            <p className="eyebrow">{t("cats.eyebrow")}</p>
            <h2 id="cats-h" className="h-1">{t("cats.title")}</h2>
          </div>
          <p className="note"><span className="tag-demo">{t("demo.badge")}</span>{t("cats.note")}</p>
        </div>
        <div className="cats-wrap">
          <CatCard c={a} />
          <div className="cats"><CatCard c={b} /><CatCard c={c} /></div>
        </div>
      </div>
    </section>
  );
}

function Featured() {
  const { t, route } = useApp();
  const items = window.PRODUCTS.filter(p => p.featured).slice(0, 4);
  return (
    <section className="sec sec-stone" aria-labelledby="feat-h">
      <div className="wrap">
        <div className="sec-head">
          <div>
            <p className="eyebrow">{t("feat.eyebrow")}</p>
            <h2 id="feat-h" className="h-1">{t("feat.title")}</h2>
          </div>
          <a className="link" href={hrefFor(route.lang, "products")}>{t("feat.all")} {Ico.arrow()}</a>
        </div>
        <div className="grid">{items.map(p => <ProductCard key={p.id} p={p} />)}</div>
        <p className="ref-note">{t("cat.demo")}</p>
      </div>
    </section>
  );
}

function InspirationTeaser() {
  const { t, route } = useApp();
  const S = window.SPACES;
  const cls = ["insp-a", "insp-b", "insp-c", "insp-d"];
  return (
    <section className="sec" aria-labelledby="insp-h">
      <div className="wrap">
        <div className="sec-head">
          <div>
            <p className="eyebrow">{t("insp.eyebrow")}</p>
            <h2 id="insp-h" className="h-1">{t("insp.title")}</h2>
          </div>
          <a className="link" href={hrefFor(route.lang, "inspiration")}>{t("insp.more")} {Ico.arrow()}</a>
        </div>
        <div className="insp">
          {S.map((s, i) => (
            <a key={s.id} className={"insp-item " + cls[i]} href={hrefFor(route.lang, "inspiration", null, "space=" + s.id)}>
              <img src={s.img} alt="" loading="lazy" />
              <div className="over">
                <div><h3>{t("space." + s.id)}</h3><p>{t("space." + s.id + ".d")}</p></div>
                <span className="arrow" style={{ width: 40, height: 40, border: "1px solid rgba(255,255,255,.5)", display: "grid", placeItems: "center", flex: "none" }}>{Ico.arrow()}</span>
              </div>
            </a>
          ))}
        </div>
        <p className="ref-note">{t("ip.ref")}</p>
      </div>
    </section>
  );
}

function Steps() {
  const { t } = useApp();
  return (
    <section className="sec-tight" aria-labelledby="steps-h" style={{ paddingTop: 0 }}>
      <div className="wrap">
        <div className="sec-head" style={{ marginBottom: 28 }}>
          <div>
            <p className="eyebrow">{t("steps.eyebrow")}</p>
            <h2 id="steps-h" className="h-2">{t("steps.title")}</h2>
          </div>
        </div>
        <ol className="steps" style={{ listStyle: "none", margin: 0, padding: 0 }}>
          {[1, 2, 3].map(n => (
            <li key={n} className="step">
              <span className="step-n">0{n}</span>
              <h3>{t(`step${n}.t`)}</h3>
              <p>{t(`step${n}.d`)}</p>
              {n < 3 && <span className="step-arrow">{Ico.arrow(14)}</span>}
            </li>
          ))}
        </ol>
      </div>
    </section>
  );
}

/* Visitor section — single language only. TR: local "plan your visit"; EN/BG/EL: cross-border visitors. */
function International() {
  const { t, route } = useApp();
  return (
    <section className="sec sec-stone" aria-labelledby="intl-h">
      <div className="wrap intl">
        <div>
          <p className="eyebrow">{t("intl2.eyebrow")}</p>
          <h2 id="intl-h" className="h-1" style={{ marginTop: 16 }}>{t("intl2.title")}</h2>
          <p className="lead" style={{ marginTop: 20 }}>{t("intl2.text")}</p>
          <div className="btn-row" style={{ marginTop: 28 }}>
            <a className="btn btn-primary" href={hrefFor(route.lang, "quote")}>{t("hero.cta2")}</a>
            <a className="btn btn-ghost" href={hrefFor(route.lang, "contact")}>{Ico.pin()} {t("visit.directions")}</a>
          </div>
        </div>
        <ol className="intl-points">
          {[1, 2, 3, 4].map(n => (
            <li key={n}>
              <span className="step-n">0{n}</span>
              <div><h3>{t(`intl2.p${n}.t`)}</h3><p>{t(`intl2.p${n}.d`)}</p></div>
            </li>
          ))}
        </ol>
      </div>
    </section>
  );
}

function VisitBlock({ compact }) {
  const { t } = useApp();
  const S = window.SITE;
  const { route } = useApp();
  const hl = { tr: "tr", en: "en", bg: "bg", el: "el" }[route.lang];
  const dirUrl = "https://www.google.com/maps/dir/?api=1&destination=" + encodeURIComponent("Meriç Seramik, Edirne") + "&hl=" + hl;
  const openUrl = "https://maps.google.com/?cid=" + S.mapsCid + "&hl=" + hl;
  return (
    <div className="visit">
      <figure className="map" style={{ minHeight: compact ? 360 : 460 }}>
        <iframe src={S.mapsEmbed.split("{hl}").join(hl)} title={t("map.title")} loading="lazy"
          referrerPolicy="strict-origin-when-cross-origin" allowFullScreen></iframe>
        <a className="map-open" href={openUrl} target="_blank" rel="noopener">{t("map.open")} ↗</a>
      </figure>
      <div>
        <p className="eyebrow">{t("visit.eyebrow")}</p>
        <h2 className="h-1" style={{ marginTop: 16 }}>{t("visit.title")}</h2>
        <p className="lead" style={{ marginTop: 18 }}>{t("visit.text")}</p>
        <ul className="info-list">
          <li><span className="k">{t("visit.address")}</span><address className="addr">{S.address ? <>Nilüfer Cd. 28/2, İstasyon<br />22100 Edirne Merkez / Edirne</> : <Pending />}<br /><span className="muted small">{t("fm.c.TR")}</span></address></li>
          <li><span className="k">{t("visit.phone")}</span>{S.phone ? <a href={"tel:" + S.phone} className="tel-link">{S.phoneDisplay}</a> : <Pending />}</li>
          <li><span className="k">{t("visit.hours")}</span>{S.hours ? (
            <dl className="hours">
              {S.hours.map(r => <div key={r.days}><dt>{t("hr." + r.days)}</dt><dd>{r.open} – {r.close}</dd></div>)}
            </dl>) : <Pending />}</li>
          <li><span className="k">{t("visit.instagram")}</span><a href={S.instagram} target="_blank" rel="noopener">{S.instagramHandle}</a></li>
        </ul>
        <div className="btn-row">
          <a className="btn btn-dark" href={dirUrl} target="_blank" rel="noopener">{Ico.pin()} {t("visit.directions")}</a>
          {S.phone && <a className="btn btn-line" href={"tel:" + S.phone}>{t("visit.call")}</a>}
          <WaButton className="btn btn-line" />
        </div>
      </div>
    </div>
  );
}

function Faq() {
  const { t, route } = useApp();
  return (
    <section className="sec" aria-labelledby="faq-h">
      <div className="wrap faq">
        <div>
          <p className="eyebrow">{t("faq.eyebrow")}</p>
          <h2 id="faq-h" className="h-1" style={{ marginTop: 16 }}>{t("faq.title")}</h2>
          <ul className="faq-cats">
            {window.CATEGORIES.map(c => (
              <li key={c.id}><a href={hrefFor(route.lang, "category", c.id)}>{t("cg.faq", { cat: window.SEO_CONTENT[route.lang].cats[c.id].h1 })} {Ico.arrow(14)}</a></li>
            ))}
          </ul>
        </div>
        <FaqList items={faqsFor(route)} />
      </div>
    </section>
  );
}

function HomePage() {
  return (
    <>
      <Hero />
      <Categories />
      <Featured />
      <InspirationTeaser />
      <Steps />
      <International />
      <section className="sec" aria-label="Visit"><div className="wrap"><VisitBlock /></div></section>
      <div className="wrap"><hr style={{ border: 0, borderTop: "1px solid var(--line)", margin: 0 }} /></div>
      <Faq />
    </>
  );
}

Object.assign(window, { HomePage, VisitBlock, Faq });
