// Story, Menu, Branches, Catering, Karachi Grill, Order, Press

// ============ STORY ============
function StoryPage({ setPage }) {
  const milestones = [
    { y: "1967", h: "A cruise ship docks in Dubai.", t: "Haji Mohammad Farooq steps off with very little. He works any job he can find." },
    { y: "1973", h: "AED 60,000 for Tipu Sultan.", t: "He buys a small Deira restaurant — AED 20K down, the rest paid as the karahi-pans go on the fire. Karachi Darbar opens.", big: true },
    { y: "1980s", h: "Deira becomes home.", t: "Muteena, Naif, Karama — branch by branch, the family expands inside Old Dubai." },
    { y: "1990s", h: "Crossing the creek.", t: "Bur Dubai, Satwa, then Al Qusais — the Pakistani community follows new neighbourhoods." },
    { y: "2003", h: "Industrial-scale kitchen.", t: "Al Qusais Industrial 3 commissioned. The family is no longer a restaurant — it is a food company." },
    { y: "2010", h: "First in our category.", t: "ISO 9001, ISO 22000 and HACCP — the first Pakistani restaurant chain in the UAE to certify." },
    { y: "2018", h: "AED 14 million to a kidney hospital.", t: "Ayaz Farooq commits the family's largest charitable contribution to date — a kidney care unit back home." },
    { y: "2020", h: "Karachi Grill opens.", t: "Jumeirah 2, Villa 290 — fine-dining offshoot for the next generation of expats. Same kitchen DNA, different room." },
    { y: "2026", h: "22 branches. 100,000 meals a day.", t: "Three emirates. One family. One central kitchen. The roti is still hot." },
  ];
  return (
    <main className="story">
      <section className="story__hero">
        <div className="container">
          <div className="kicker kicker--cream">Our Story · 52 Years</div>
          <h1 className="h1 story__h1">From a Deira restaurant called Tipu Sultan<br/>to 22 branches across three emirates.</h1>
          <p className="lead lead--cream">A family business, plainly told.</p>
        </div>
      </section>

      <section className="section">
        <div className="container founder--story">
          <div className="founder__photo">
            <div className="founder__placeholder founder__placeholder--lg">
              <div className="ph__label">Founder portrait</div>
              <div className="ph__note">Haji Mohammad Farooq · request from family for launch</div>
            </div>
          </div>
          <div className="founder__copy">
            <blockquote className="pullquote pullquote--lg">
              "He bought it for AED 60,000. Twenty down, the rest from the kitchen as it earned. That's how Karachi Darbar started."
            </blockquote>
            <p className="founder__rest founder__rest--lg">
              In 1967, Haji Mohammad Farooq landed in Dubai from Pakistan with very little. Six years later he bought
              a small Deira restaurant called <em>Tipu Sultan</em>. Fifty-two years on, his son Ayaz runs the group
              — twenty-two branches, one central kitchen, three emirates, a hundred thousand meals a day.
            </p>
          </div>
        </div>
      </section>

      <section className="timeline-section">
        <div className="container">
          <div className="kicker">The arc</div>
          <h2 className="h2">Fifty-two years, told in nine moments.</h2>
          <ol className="timeline">
            {milestones.map((m, i) => (
              <li key={i} className={`tl ${m.big ? "tl--big" : ""}`}>
                <div className="tl__year">{m.y}</div>
                <div className="tl__dot"><span></span></div>
                <div className="tl__body">
                  <h3 className="tl__h">{m.h}</h3>
                  <p className="tl__t">{m.t}</p>
                </div>
              </li>
            ))}
          </ol>
        </div>
      </section>

      <section className="section section--cream">
        <div className="container ayaz">
          <div className="ayaz__quote">
            <div className="big-quote">"</div>
            <p>
              We are not chefs in white jackets. We are a family that fed a city, and the city kept showing up.
              You do not get fifty-two years on AED 21 nihari by being clever. You get it by being on time, every day.
            </p>
            <div className="ayaz__attr">
              <strong>Ayaz Farooq</strong><br/>
              Son of the founder, group CEO
            </div>
          </div>
          <div className="ayaz__side">
            <div className="cert-card">
              <h4>First in category</h4>
              <div className="cert-row">
                <span className="cert cert--lg">ISO 9001</span>
                <span className="cert cert--lg">ISO 22000</span>
                <span className="cert cert--lg">HACCP</span>
              </div>
              <p>The first Pakistani restaurant chain in the UAE to certify across quality, food-safety and hazard control.</p>
            </div>
            <div className="cert-card cert-card--accent">
              <h4>AED 14M to a kidney hospital</h4>
              <p>Our largest charitable commitment. A reminder of what the karahi pays for.</p>
            </div>
          </div>
        </div>
      </section>

      <section className="footer-cta">
        <div className="container footer-cta__inner">
          <h2 className="h2 footer-cta__h">Visit the place where it started.</h2>
          <div className="footer-cta__buttons">
            <button className="btn btn--primary btn--lg" onClick={() => setPage("branches")}>Find a branch</button>
            <button className="btn btn--ghost btn--lg" onClick={() => setPage("menu")}>See the menu</button>
          </div>
        </div>
      </section>
    </main>
  );
}

// ============ MENU ============
function MenuPage() {
  const [active, setActive] = React.useState("signatures");
  const refs = React.useRef({});
  const scrollTo = (id) => {
    setActive(id);
    const el = refs.current[id];
    if (el) window.scrollTo({ top: el.offsetTop - 140, behavior: "smooth" });
  };
  React.useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY + 200;
      for (const cat of window.MENU) {
        const el = refs.current[cat.id];
        if (el && y >= el.offsetTop) setActive(cat.id);
      }
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <main className="menu">
      <section className="menu__head">
        <div className="container">
          <div className="kicker">The menu · AED prices · per branch may vary</div>
          <h1 className="h1">Pakistani, Mughlai, Indian,<br/>Sea Food, Indo-Chinese.</h1>
          <p className="lead">Five cuisine pillars. One karahi. AED 20–40 a head.</p>
        </div>
      </section>

      <div className="menu__chips" role="tablist">
        <div className="container menu__chips-inner">
          {window.MENU.map(cat => (
            <button key={cat.id}
              className={`chip ${active === cat.id ? "chip--active" : ""}`}
              onClick={() => scrollTo(cat.id)}>
              {cat.title}
            </button>
          ))}
        </div>
      </div>

      <div className="container menu__body">
        {window.MENU.map(cat => (
          <section key={cat.id} ref={el => refs.current[cat.id] = el} id={cat.id} className="menu__cat">
            <header className="menu__cat-head">
              <h2 className="h3">{cat.title}</h2>
              {cat.subtitle && <p className="menu__cat-sub">{cat.subtitle}</p>}
            </header>
            {cat.id === "signatures" ? (
              <div className="sig-grid sig-grid--menu">
                {cat.items.map(it => (
                  <article key={it.name} className="sig">
                    {it.hero && <div className="sig__img"><img src={it.hero} alt={it.name} /></div>}
                    <div className="sig__body">
                      <div className="sig__row">
                        <h3 className="sig__name">{it.name}</h3>
                        <div className="sig__price">AED <b>{it.price}</b></div>
                      </div>
                      {it.desc && <p className="sig__desc">{it.desc}</p>}
                      {it.tag && <span className="dish-tag">{it.tag}</span>}
                    </div>
                  </article>
                ))}
              </div>
            ) : (
              <div className="dishlist">
                {cat.items.map(it => (
                  <div key={it.name} className={`dish ${it.signature ? "dish--star" : ""}`}>
                    <div className="dish__name">
                      {it.signature && <span className="dish__star"><StarIcon /></span>}
                      {it.name}
                    </div>
                    <div className="dish__dots" aria-hidden></div>
                    <div className="dish__price">AED <b>{it.price}</b></div>
                  </div>
                ))}
              </div>
            )}
          </section>
        ))}
      </div>
    </main>
  );
}

// ============ BRANCHES ============
function haversine(a, b) {
  const toRad = (x) => x * Math.PI / 180;
  const R = 6371;
  const dLat = toRad(b.lat - a.lat);
  const dLng = toRad(b.lng - a.lng);
  const x = Math.sin(dLat/2)**2 + Math.cos(toRad(a.lat)) * Math.cos(toRad(b.lat)) * Math.sin(dLng/2)**2;
  return 2 * R * Math.asin(Math.sqrt(x));
}

function BranchesPage() {
  const [filter, setFilter] = React.useState("All");
  const [user, setUser] = React.useState(null);
  const [geoState, setGeoState] = React.useState("idle"); // idle | locating | denied | done | mock
  const [open, setOpen] = React.useState(null);

  const filters = ["All", "Dubai", "Sharjah", "Ajman", "24 Hours"];
  let branches = window.BRANCHES.filter(b => !b.isGrill);
  if (filter === "Dubai" || filter === "Sharjah" || filter === "Ajman") branches = branches.filter(b => b.emirate === filter);
  if (filter === "24 Hours") branches = branches.filter(b => b.hours === "24 hours");
  if (user) {
    branches = branches.map(b => ({ ...b, dist: haversine(user, b) })).sort((a, b) => a.dist - b.dist);
  }

  const locate = () => {
    setGeoState("locating");
    if (!navigator.geolocation) {
      // mock to Karama
      setTimeout(() => { setUser({ lat: 25.244, lng: 55.301 }); setGeoState("mock"); }, 700);
      return;
    }
    navigator.geolocation.getCurrentPosition(
      (pos) => { setUser({ lat: pos.coords.latitude, lng: pos.coords.longitude }); setGeoState("done"); },
      () => {
        // permission denied — mock for prototype
        setTimeout(() => { setUser({ lat: 25.244, lng: 55.301 }); setGeoState("mock"); }, 400);
      },
      { timeout: 4000 }
    );
  };

  return (
    <main className="branches">
      <section className="branches__head">
        <div className="container">
          <div className="kicker">Find your branch · 22 outlets · 3 emirates</div>
          <h1 className="h1">From Karama to Ajman.<br/>The one nearest you, mapped.</h1>
          <p className="lead">The old site listed 22 phone numbers with no names attached. This one knows where you are.</p>

          <div className="branches__toolbar">
            <button className="btn btn--primary btn--lg" onClick={locate} disabled={geoState === "locating"}>
              <CompassIcon />
              {geoState === "idle" && "Use my location"}
              {geoState === "locating" && "Locating…"}
              {(geoState === "done" || geoState === "mock") && "Sorted by distance"}
              {geoState === "denied" && "Try again"}
            </button>
            <div className="chips">
              {filters.map(f => (
                <button key={f} className={`chip ${filter === f ? "chip--active" : ""}`} onClick={() => setFilter(f)}>{f}</button>
              ))}
            </div>
            <div className="branches__count">
              {branches.length} branch{branches.length === 1 ? "" : "es"}{user ? " · sorted by distance" : ""}
            </div>
          </div>

          {geoState === "mock" && (
            <div className="hint">
              Demo location used (Al Karama). On the live site this reads your real position.
            </div>
          )}
        </div>
      </section>

      <section className="branches__list">
        <div className="container">
          {user && branches[0] && (
            <article className="branch branch--nearest" onClick={() => setOpen(branches[0].id)}>
              <div className="branch__badge">Your nearest · {branches[0].dist.toFixed(1)} km</div>
              <BranchCardBody b={branches[0]} />
            </article>
          )}
          <div className="branch-grid">
            {(user ? branches.slice(1) : branches).map(b => (
              <article key={b.id} className={`branch ${b.flagship ? "branch--flag" : ""}`} onClick={() => setOpen(b.id)}>
                <BranchCardBody b={b} user={user} />
              </article>
            ))}
          </div>
        </div>
      </section>

      {open && <BranchSheet b={branches.find(x => x.id === open) || window.BRANCHES.find(x => x.id === open)} onClose={() => setOpen(null)} />}
    </main>
  );
}

function BranchCardBody({ b, user }) {
  return (
    <>
      <div className="branch__top">
        <div>
          <div className="branch__emirate">{b.emirate} · {b.area}</div>
          <h3 className="branch__name">{b.name}</h3>
        </div>
        <div className="branch__pill">
          {b.hours === "24 hours" ? <span className="badge badge--24">24h</span> : <span className="badge">5–2</span>}
          {b.flagship && <span className="badge badge--gold">Flagship</span>}
        </div>
      </div>
      <div className="branch__addr">{b.address}</div>
      <div className="branch__meta">
        <span><ClockIcon /> {b.hours}</span>
        <span><PhoneIcon /> {b.phone}</span>
        {b.dist != null && <span><PinIcon /> {b.dist.toFixed(1)} km</span>}
      </div>
      {b.rating && (
        <div className="branch__rating"><StarIcon /> {b.rating} · {b.ratingSrc}</div>
      )}
    </>
  );
}

function BranchSheet({ b, onClose }) {
  React.useEffect(() => {
    const k = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", k);
    return () => window.removeEventListener("keydown", k);
  }, [onClose]);
  return (
    <div className="sheet" onClick={onClose}>
      <div className="sheet__panel" onClick={e => e.stopPropagation()}>
        <button className="sheet__close" onClick={onClose} aria-label="Close">×</button>
        <div className="sheet__top">
          <div className="kicker">{b.emirate} · {b.area}</div>
          <h2 className="h2">{b.name}</h2>
          <div className="branch__pill">
            {b.hours === "24 hours" ? <span className="badge badge--24">Open 24 hours</span> : <span className="badge">Daily 5 AM – 2 AM</span>}
            {b.flagship && <span className="badge badge--gold">Flagship</span>}
          </div>
        </div>

        <div className="sheet__map">
          <div className="map-mock">
            <div className="map-mock__grid"></div>
            <div className="map-mock__pin"><PinIcon /></div>
            <div className="map-mock__caption">Google Maps · Place ID embed (no goo.gl short-links)</div>
          </div>
        </div>

        <div className="sheet__grid">
          <Field icon={<PinIcon />} label="Address" value={b.address} />
          <Field icon={<PhoneIcon />} label="Phone" value={<a href={`tel:${b.phone.replace(/\s/g,'')}`}>{b.phone}</a>} />
          <Field icon={<ClockIcon />} label="Hours" value={b.hours} />
          <Field icon={<CarIcon />} label="Parking" value={b.parking} />
        </div>

        <div className="sheet__order">
          <h4>Order from this branch</h4>
          <div className="order-platforms">
            <PlatformBadge name="Talabat" href={b.delivery?.talabat || "https://www.talabat.com/uae/karachi-darbar"} />
            <PlatformBadge name="Deliveroo" href={b.delivery?.deliveroo || "#"} />
            <PlatformBadge name="Zomato" href="#" />
            <PlatformBadge name="Careem" href="#" />
            <PlatformBadge name="EazyDiner" href="#" />
          </div>
        </div>

        <div className="sheet__actions">
          <a className="btn btn--primary btn--lg" href={`tel:${b.phone.replace(/\s/g,'')}`}><PhoneIcon /> Call branch</a>
          <a className="btn btn--gold btn--lg" target="_blank" rel="noreferrer"
             href={`https://www.google.com/maps/dir/?api=1&destination=${b.lat},${b.lng}`}>
            <CompassIcon /> Directions
          </a>
        </div>
      </div>
    </div>
  );
}

function Field({ icon, label, value }) {
  return (
    <div className="field">
      <div className="field__icon">{icon}</div>
      <div>
        <div className="field__label">{label}</div>
        <div className="field__value">{value}</div>
      </div>
    </div>
  );
}

function PlatformBadge({ name, href }) {
  return (
    <a className="platform" href={href} target="_blank" rel="noreferrer">
      <span className="platform__dot"></span>
      <span className="platform__name">{name}</span>
      <ArrowIcon />
    </a>
  );
}

Object.assign(window, { StoryPage, MenuPage, BranchesPage });
