const MNS = window.SburgerDesignSystem_d72664;
const { Button, IconButton, Icon, Card, SectionHeading, MenuItemCard, StarRating } = MNS;

function isOpenNow() {
  const d = new Date();
  const day = d.getDay();
  if (day === 2) return false;
  const mins = d.getHours() * 60 + d.getMinutes();
  return mins >= 19 * 60 && mins < 22 * 60;
}

function MobileHeader() {
  return (
    <header className="sb-safe-top" style={{ position: "sticky", top: 0, zIndex: 40, background: "var(--ink-900)", borderBottom: "var(--border-w-sign) solid var(--red-600)", paddingLeft: "var(--gutter-mobile)", paddingRight: "var(--gutter-mobile)", minHeight: 60, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
      <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
        <img src="favicon-32.png" alt="" style={{ height: 28, width: "auto", borderRadius: 6 }} />
        <span style={{ fontFamily: "var(--font-display)", fontSize: 22, lineHeight: 1, color: "var(--sb-yellow)", textTransform: "uppercase", display: "inline-block", transform: "skewX(var(--display-skew))" }}>Sburger</span>
      </span>
      <IconButton icon="phone" label="Chiama" size="sm" variant="secondary" href={window.PHONE_TEL} />
    </header>
  );
}

function MobileIntro() {
  const open = isOpenNow();
  return (
    <div style={{ background: "var(--ink-900)", backgroundImage: "var(--plate-dark)", padding: "var(--space-6) var(--gutter-mobile)", display: "grid", gap: "var(--space-3)" }}>
      <span style={{ font: "var(--type-eyebrow)", letterSpacing: "var(--ls-eyebrow)", textTransform: "uppercase", color: "var(--yellow-500)" }}>San Benedetto del Tronto · Via Volturno 11</span>
      <h1 style={{ color: "var(--text-on-dark)", fontSize: 34, lineHeight: 0.95, margin: 0, textTransform: "uppercase", fontFamily: "var(--font-display)", transform: "skewX(-2deg)" }}>Ordina il tuo smash burger</h1>
      <div style={{ display: "flex", alignItems: "center", gap: "var(--space-3)", flexWrap: "wrap" }}>
        <StarRating value={4.6} count={72} size={14} onDark />
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "3px 10px", borderRadius: "var(--radius-pill)", background: open ? "var(--veggie-bg)" : "var(--ink-700)", color: open ? "var(--veggie)" : "var(--text-on-dark-muted)", font: "var(--type-eyebrow)", fontSize: 11, textTransform: "uppercase" }}>
          <span style={{ width: 7, height: 7, borderRadius: "50%", background: open ? "var(--veggie)" : "var(--ink-400)" }} />
          {open ? "Aperto ora" : "Chiuso ora"}
        </span>
      </div>
      <p style={{ margin: 0, font: "var(--type-body-sm)", fontSize: "var(--text-sm)", color: "var(--text-on-dark-muted)" }}>Asporto 19:00–22:00 · Chiuso il martedì · Si paga al ritiro</p>
    </div>
  );
}

function MobileMenu() {
  return (
    <section id="Menu" style={{ padding: "var(--space-6) var(--gutter-mobile)", display: "grid", gap: "var(--space-4)", background: "var(--surface-page)", backgroundImage: "var(--grain)", backgroundSize: "var(--grain-size)" }}>
      <SectionHeading eyebrow="Il menu" title="Sei panini" />
      <div style={{ display: "grid", gap: "var(--space-4)" }}>
        {window.SB.menu.map((m) => (
          <MenuItemCard key={m.name} layout="column" {...m} style={{ height: "auto" }} />
        ))}
      </div>
    </section>
  );
}

function MobileOrder() {
  const channels = [
    { label: "Ordina su Yellgo", note: "Asporto diretto", icon: "shopping-bag", href: window.ORDER_LINKS.yellgo, variant: "primary" },
    { label: "Ordina su Deliveroo", note: "Consegna a domicilio", icon: "bike", href: window.ORDER_LINKS.deliveroo, variant: "secondary" },
    { label: "Ordina su Glovo", note: "Consegna a domicilio", icon: "bike", href: window.ORDER_LINKS.glovo, variant: "outline" },
  ];
  return (
    <section id="ordina" style={{ padding: "var(--space-6) var(--gutter-mobile) var(--space-8)", background: "var(--ink-800)", backgroundImage: "var(--plate-dark)", display: "grid", gap: "var(--space-4)" }}>
      <SectionHeading onDark eyebrow="Come ordinare" title="Scegli dove" sub="Il sito non gestisce pagamenti: si ordina tramite una di queste piattaforme." />
      <div style={{ display: "grid", gap: "var(--space-3)" }}>
        {channels.map((c) => (
          <Button key={c.label} variant={c.variant} full onDark={c.variant !== "secondary"} href={c.href} target="_blank" rel="noopener noreferrer" style={{ justifyContent: "flex-start", gap: "var(--space-3)", height: 56 }}>
            <Icon name={c.icon} size={18} />
            <span style={{ display: "grid", textAlign: "left", lineHeight: 1.2 }}>
              <span>{c.label}</span>
            </span>
          </Button>
        ))}
      </div>
    </section>
  );
}

function MobileFindUs() {
  return (
    <section id="Dove siamo" style={{ padding: "var(--space-6) var(--gutter-mobile)", background: "var(--gingham-base)", backgroundImage: "var(--gingham)" }}>
      <Card tone="light" border="sign" sticker style={{ display: "grid", gap: "var(--space-4)" }}>
        <SectionHeading eyebrow="Dove siamo" title="Via Volturno 11" sub="63074 San Benedetto del Tronto (AP)" />
        <div style={{ borderRadius: "var(--radius-md)", overflow: "hidden", height: 200, border: "var(--border-w-thick) solid var(--ink-900)" }}>
          <iframe title="Mappa — Sburger" src="https://www.openstreetmap.org/export/embed.html?bbox=13.8744%2C42.9503%2C13.8844%2C42.9553&layer=mapnik&marker=42.9527962%2C13.8794086" style={{ width: "100%", height: "100%", border: "none" }} loading="lazy" />
        </div>
        <div style={{ display: "grid", gap: 2 }}>
          {window.SB.hours.map(([d, h]) => (
            <div key={d} style={{ display: "flex", justifyContent: "space-between", padding: "5px 0", borderBottom: "var(--border-w) solid var(--border-hairline)", font: "var(--type-body-sm)", fontSize: "var(--text-sm)", color: h === "Chiuso" ? "var(--text-faint)" : "var(--text-body)" }}>
              <span>{d}</span>
              <span style={{ fontFamily: "var(--font-condensed)", fontWeight: "var(--weight-bold)", color: h === "Chiuso" ? "var(--red-600)" : "var(--text-strong)" }}>{h}</span>
            </div>
          ))}
        </div>
        <div style={{ display: "flex", gap: "var(--space-3)" }}>
          <Button variant="primary" full href={window.PHONE_TEL}><Icon name="phone" size={16} /> Chiama</Button>
          <Button variant="outline" full href={window.MAPS_DIRECTIONS} target="_blank" rel="noopener noreferrer"><Icon name="navigation" size={16} /> Indicazioni</Button>
        </div>
      </Card>
    </section>
  );
}

function MobileFooter() {
  return (
    <footer style={{ background: "var(--ink-900)", color: "var(--text-on-dark)", padding: "var(--space-6) var(--gutter-mobile) 104px", display: "grid", gap: "var(--space-2)", textAlign: "center" }}>
      <span style={{ font: "var(--type-eyebrow)", letterSpacing: "var(--ls-eyebrow)", textTransform: "uppercase", color: "var(--yellow-500)" }}>Sburger</span>
      <a href="https://instagram.com/sburgersbt" target="_blank" rel="noopener noreferrer" style={{ color: "var(--text-on-dark-muted)", fontSize: 14, textDecoration: "none" }}>@sburgersbt</a>
      <span style={{ fontSize: 12, color: "var(--text-faint)" }}>© 2026 Sburger — The Original Smash Burger</span>
    </footer>
  );
}

function MobileBottomBar() {
  return (
    <div style={{ position: "fixed", left: 0, right: 0, bottom: 0, zIndex: 50, display: "flex", gap: "var(--space-2)", padding: "var(--space-3) var(--gutter-mobile)", paddingBottom: "max(var(--space-3), env(safe-area-inset-bottom))", background: "var(--white)", borderTop: "var(--border-w-thick) solid var(--ink-900)", boxShadow: "0 -8px 24px rgba(0,0,0,.15)" }}>
      <Button variant="outline" href={window.PHONE_TEL} aria-label="Chiama" style={{ flex: "0 0 auto", width: 56, padding: 0 }}>
        <Icon name="phone" size={18} />
      </Button>
      <Button variant="primary" full onClick={() => window.scrollToSection("ordina")}>Ordina ora</Button>
    </div>
  );
}

function ShareGlyph() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--yellow-500)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flex: "0 0 auto" }}>
      <path d="M12 2v13" />
      <path d="m8 6 4-4 4 4" />
      <path d="M20 12v7a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-7" />
    </svg>
  );
}

function AddToHomeScreenPrompt() {
  const [visible, setVisible] = React.useState(false);
  const [platform, setPlatform] = React.useState(null);
  const deferredPrompt = React.useRef(null);

  React.useEffect(() => {
    const forced = new URLSearchParams(window.location.search).get("a2hs");
    if (forced === "ios" || forced === "android") {
      setPlatform(forced);
      setVisible(true);
      return;
    }

    const isStandalone = window.navigator.standalone === true || window.matchMedia("(display-mode: standalone)").matches;
    if (isStandalone) return;
    if (localStorage.getItem("sb_a2hs_dismissed") === "1") return;

    const ua = window.navigator.userAgent;
    const isIOS = /iPad|iPhone|iPod/.test(ua) && !window.MSStream;

    if (isIOS) {
      const t = setTimeout(() => { setPlatform("ios"); setVisible(true); }, 1800);
      return () => clearTimeout(t);
    }

    const handler = (e) => {
      e.preventDefault();
      deferredPrompt.current = e;
      setPlatform("android");
      setVisible(true);
    };
    window.addEventListener("beforeinstallprompt", handler);
    return () => window.removeEventListener("beforeinstallprompt", handler);
  }, []);

  const dismiss = () => {
    setVisible(false);
    localStorage.setItem("sb_a2hs_dismissed", "1");
  };

  const installAndroid = async () => {
    if (!deferredPrompt.current) return;
    deferredPrompt.current.prompt();
    await deferredPrompt.current.userChoice;
    deferredPrompt.current = null;
    dismiss();
  };

  if (!visible) return null;

  return (
    <div className="sb-a2hs-banner" style={{ position: "fixed", left: 12, right: 12, bottom: 84, zIndex: 60, background: "var(--ink-800)", color: "var(--text-on-dark)", borderRadius: "var(--radius-lg)", border: "var(--border-w-thick) solid var(--ink-900)", boxShadow: "var(--shadow-sticker)", padding: "14px 14px 16px", display: "grid", gap: 10 }}>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
        <img src="icon-192.png" alt="" style={{ width: 40, height: 40, borderRadius: 10, flex: "0 0 auto" }} />
        <div style={{ flex: 1, display: "grid", gap: 2 }}>
          <strong style={{ fontFamily: "var(--font-display)", fontSize: 15, textTransform: "uppercase", letterSpacing: ".02em" }}>Installa Sburger</strong>
          <span style={{ font: "var(--type-body-sm)", fontSize: 13, color: "var(--text-on-dark-muted)" }}>
            {platform === "ios" ? "Aggiungila alla schermata Home per ordinare più veloce, come un'app." : "Aggiungi l'app alla schermata Home per ordinare più veloce."}
          </span>
        </div>
        <button type="button" onClick={dismiss} aria-label="Chiudi" style={{ background: "transparent", border: "none", color: "var(--text-on-dark-muted)", fontSize: 18, lineHeight: 1, cursor: "pointer", padding: 4 }}>✕</button>
      </div>
      {platform === "ios" ? (
        <>
          <div style={{ display: "flex", alignItems: "center", gap: 8, background: "rgba(251,243,228,.08)", borderRadius: 10, padding: "8px 10px", font: "var(--type-body-sm)", fontSize: 13 }}>
            <ShareGlyph />
            <span>Tocca <strong>Condividi</strong>, poi <strong>"Aggiungi alla schermata Home"</strong></span>
          </div>
          <div style={{ display: "flex", justifyContent: "center" }}>
            <span className="sb-a2hs-bounce" style={{ fontSize: 20, color: "var(--yellow-500)", lineHeight: 1 }}>⌄</span>
          </div>
        </>
      ) : (
        <button type="button" onClick={installAndroid} style={{ height: 44, border: "var(--border-w-thick) solid var(--ink-900)", borderRadius: "var(--radius-md)", background: "var(--yellow-500)", color: "var(--ink-900)", fontWeight: "var(--weight-bold)", textTransform: "uppercase", letterSpacing: "var(--ls-badge)", fontSize: 13, cursor: "pointer" }}>
          Installa l'app
        </button>
      )}
    </div>
  );
}

function MobileApp() {
  return (
    <div>
      <MobileHeader />
      <MobileIntro />
      <MobileMenu />
      <MobileOrder />
      <MobileFindUs />
      <MobileFooter />
      <MobileBottomBar />
      <AddToHomeScreenPrompt />
    </div>
  );
}

Object.assign(window, { MobileApp });
