/* Sentosa Marketplace - Buyer Portal screens: Login + Catalogue */

function LoginScreen({ onLogin }) {
  const [email, setEmail] = React.useState("bookings@wanderlust.com");
  const [pw, setPw] = React.useState("trade-access");
  return (
    <div style={{ minHeight: "100vh", display: "flex" }}>
      {/* Left brand panel */}
      <div style={{ flex: "1 1 46%", background: "var(--black)", color: "#fff", padding: "48px 56px", display: "flex", flexDirection: "column", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
          <Logo height={30} href={null} />
          <a href="../../index.html" style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 13,
            color: "#9A9A9A", textDecoration: "none", fontWeight: 500 }}>
            <Icon name="arrow-left" size={15} />Back to marketplace home
          </a>
        </div>
        <div>
          <div style={{ fontSize: 13, fontWeight: 600, letterSpacing: ".06em", textTransform: "uppercase", color: "var(--orange-300)", marginBottom: 16 }}>B2B Marketplace</div>
          <h1 className="display" style={{ color: "#fff", maxWidth: 460, marginBottom: 18 }}>Sentosa island products, at trade rates.</h1>
          <p style={{ fontSize: 17, lineHeight: 1.6, color: "#C9C9C9", maxWidth: 420 }}>Browse and book attraction tickets, experiences and MICE venues from Sentosa's island partners - in one accredited marketplace.</p>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: "#9A9A9A" }}>
          <Icon name="lock" size={14} /> Secure access · Hosted in Singapore (AWS)
        </div>
      </div>
      {/* Right form */}
      <div style={{ flex: "1 1 54%", background: "var(--surface)", display: "flex", alignItems: "center", justifyContent: "center", padding: 32 }}>
        <div style={{ width: "100%", maxWidth: 380 }}>
          <h2 style={{ marginBottom: 4 }}>Sign in to your trade account</h2>
          <p className="caption" style={{ marginBottom: 28 }}>Use the credentials issued to your accredited agency.</p>
          <form onSubmit={e => { e.preventDefault(); onLogin(); }} style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Field label="Agency email" required type="email" placeholder="you@agency.com" value={email} onChange={e => setEmail(e.target.value)} />
            <Field label="Password" required type="password" placeholder="••••••••" value={pw} onChange={e => setPw(e.target.value)} />
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 13.5 }}>
              <label style={{ display: "flex", gap: 8, alignItems: "center", cursor: "pointer" }}>
                <input type="checkbox" defaultChecked style={{ width: 18, height: 18, accentColor: "var(--action)" }} /> Keep me signed in
              </label>
              <a href="#" onClick={e => e.preventDefault()} style={{ color: "var(--orange-link)", fontWeight: 600, textDecoration: "none" }}>Forgot password?</a>
            </div>
            <Btn variant="primary" full type="submit" iconRight="arrow-right">Sign in</Btn>
          </form>
          <div style={{ marginTop: 24, padding: 14, background: "var(--neutral-50)", border: "1px solid var(--border)", borderRadius: "var(--radius-md)", fontSize: 13, color: "var(--fg2)", display: "flex", gap: 10 }}>
            <Icon name="info" size={16} color="var(--info)" style={{ marginTop: 1 }} />
            <span>New trade partner? Accreditation is handled by SDC. <a href="#" onClick={e=>e.preventDefault()} style={{ color: "var(--orange-link)", fontWeight: 600 }}>Request access</a>.</span>
          </div>
        </div>
      </div>
    </div>
  );
}

function ProductCard({ p, onOpen, onAdd }) {
  const { t, tn } = useLang();
  const off = Math.round((1 - p.trade / p.rack) * 100);
  return (
    <Card pad={0} hover onClick={() => onOpen(p)} style={{ overflow: "hidden", display: "flex", flexDirection: "column" }}>
      <Photo src={p.photo} tint={p.img} alt={p.name} zoom style={{ height: 210 }}>
        {p.tag && <span style={{ position: "absolute", top: 10, left: 10 }}><Badge tone={p.tag === "MICE" ? "info" : "brand"} dot={false}>{t(p.tag)}</Badge></span>}
      </Photo>
      <div style={{ padding: 14, display: "flex", flexDirection: "column", flex: 1 }}>
        <div className="overline" style={{ color: "var(--fg2)" }}>{t(p.cat)} · {t(p.type)}</div>
        <div style={{ fontSize: 15.5, fontWeight: 600, margin: "4px 0 2px", lineHeight: 1.3 }}>{tn(p.name)}</div>
        <div style={{ fontSize: 12.5, color: "var(--fg2)", marginBottom: 10 }}>{tn(p.partner)}</div>
        <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12.5, color: "var(--fg2)", marginBottom: 12 }}>
          <Icon name="star" size={14} color="var(--warning)" /> <strong style={{ color: "var(--fg1)" }}>{p.rating}</strong> · {p.sold.replace("sold", t("sold"))}
        </div>
        <div style={{ marginTop: "auto", display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 8 }}>
          <div>
            <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
              <span style={{ fontSize: 19, fontWeight: 700 }}>S${p.trade.toFixed(2)}</span>
              {off > 0 && <span style={{ fontSize: 12.5, color: "var(--fg3)", textDecoration: "line-through" }}>S${p.rack.toFixed(2)}</span>}
            </div>
            <div style={{ fontSize: 12, color: "var(--fg2)" }}>{t("per")} {tn(p.unit)}</div>
          </div>
          <Btn size="sm" variant="secondary" icon="plus" onClick={(e) => { e.stopPropagation(); onAdd(p); }}>{t("add")}</Btn>
        </div>
      </div>
    </Card>
  );
}

function CatalogueScreen({ onOpen, onAdd, query, onAi }) {
  const { t, tn } = useLang();
  const [cat, setCat] = React.useState("All categories");
  const [partners, setPartners] = React.useState([]);   // S/No. 125: filter the catalogue by seller
  const [sort, setSort] = React.useState("featured");
  const togglePartner = (pn) => setPartners(prev => prev.includes(pn) ? prev.filter(x => x !== pn) : [...prev, pn]);
  let list = window.PRODUCTS.filter(p =>
    (cat === "All categories" || p.cat === cat) &&
    (partners.length === 0 || partners.includes(p.partner)) &&
    (!query || (p.name + p.partner).toLowerCase().includes(query.toLowerCase())));
  if (sort === "low") list = [...list].sort((a, b) => a.trade - b.trade);
  if (sort === "high") list = [...list].sort((a, b) => b.trade - a.trade);

  return (
    <div>
      {/* Hero band */}
      <div style={{ background: "var(--black)", color: "#fff" }}>
        <div style={{ maxWidth: "var(--maxw)", margin: "0 auto", padding: "40px 24px 44px" }}>
          <div className="overline" style={{ color: "var(--orange-300)" }}>{t("cat_kicker")}</div>
          <h1 style={{ color: "#fff", fontSize: "2.2rem", margin: "8px 0 10px", maxWidth: 620 }}>{t("cat_title")}</h1>
          <p style={{ fontSize: 16.5, color: "#C9C9C9", maxWidth: 560, lineHeight: 1.55 }}>{t("cat_lede")}</p>
          <div style={{ display: "flex", gap: 24, marginTop: 24, flexWrap: "wrap", alignItems: "center" }}>
            {[[t("cat_categories"), "layers"], [t("cat_partners"), "store"]].map(([label, ic]) => (
              <div key={label} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 14, color: "#E2E2E2" }}><Icon name={ic} size={17} color="var(--orange-300)" />{label}</div>
            ))}
            <button onClick={onAi} style={{ display: "inline-flex", alignItems: "center", gap: 8, background: "#262626", border: "1px solid #3a3a3a",
              color: "#fff", borderRadius: "var(--radius-pill)", padding: "8px 15px", fontSize: 13.5, fontWeight: 600, cursor: "pointer", fontFamily: "var(--font-sans)" }}>
              <Icon name="sparkles" size={16} color="var(--orange-300)" />{t("cat_ai")}
            </button>
          </div>
        </div>
      </div>

      <div style={{ maxWidth: "var(--maxw)", margin: "0 auto", padding: "28px 24px", display: "grid", gridTemplateColumns: "232px 1fr", gap: 28, alignItems: "start" }}>
        {/* Filters */}
        <aside style={{ position: "sticky", top: 96 }}>
          <Card>
            <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 12, display: "flex", alignItems: "center", gap: 8 }}><Icon name="sliders-horizontal" size={16} />{t("filters")}</div>
            <div className="overline" style={{ marginBottom: 8 }}>{t("category")}</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 2, marginBottom: 18 }}>
              {window.CATS.map(c => (
                <button key={c} onClick={() => setCat(c)} style={{ textAlign: "left", background: cat === c ? "var(--orange-50)" : "none", color: cat === c ? "var(--orange-900)" : "var(--fg1)",
                  border: 0, borderRadius: "var(--radius-sm)", padding: "8px 10px", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: cat === c ? 600 : 400 }}>{t(c)}</button>
              ))}
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
              <div className="overline" style={{ margin: 0 }}>{t("partner")}</div>
              {partners.length > 0 && (
                <button onClick={() => setPartners([])}
                  style={{ marginLeft: "auto", background: "none", border: 0, cursor: "pointer",
                    color: "var(--orange-link)", fontFamily: "var(--font-sans)", fontSize: 12, fontWeight: 600, padding: 0 }}>
                  {t("clear")}
                </button>
              )}
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 2, maxHeight: 240, overflowY: "auto" }}>
              {window.SELLERS.map(pn => {
                const n = window.PRODUCTS.filter(p => p.partner === pn).length;
                const on = partners.includes(pn);
                return (
                  <label key={pn} style={{ display: "flex", gap: 9, alignItems: "center", fontSize: 13.5,
                    color: on ? "var(--fg1)" : "var(--fg2)", fontWeight: on ? 600 : 400, cursor: "pointer",
                    padding: "6px 8px", borderRadius: "var(--radius-sm)", background: on ? "var(--orange-50)" : "transparent" }}>
                    <input type="checkbox" checked={on} onChange={() => togglePartner(pn)}
                      style={{ width: 16, height: 16, accentColor: "var(--action)", flex: "none" }} />
                    <span style={{ flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{tn(pn)}</span>
                    <span style={{ fontSize: 12, color: "var(--fg3)" }}>{n}</span>
                  </label>
                );
              })}
            </div>
          </Card>
        </aside>

        {/* Grid */}
        <div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
            <div style={{ fontSize: 14, color: "var(--fg2)" }}><strong style={{ color: "var(--fg1)" }}>{list.length}</strong> {t("products")}{cat !== "All categories" && <> · {t(cat)}</>}{partners.length > 0 && <> · {partners.length} {partners.length === 1 ? t("seller") : t("sellers")}</>}</div>
            <label style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13.5, color: "var(--fg2)" }}>
              {t("sort")}
              <select value={sort} onChange={e => setSort(e.target.value)} style={{ fontFamily: "var(--font-sans)", fontSize: 13.5, padding: "8px 10px", borderRadius: "var(--radius-md)", border: "1.5px solid var(--border)", background: "#fff" }}>
                <option value="featured">{t("sort_featured")}</option><option value="low">{t("sort_low")}</option><option value="high">{t("sort_high")}</option>
              </select>
            </label>
          </div>
          {list.length === 0
            ? <Card style={{ textAlign: "center", padding: 48, color: "var(--fg2)" }}><Icon name="search-x" size={32} color="var(--fg3)" /><div style={{ marginTop: 10, fontWeight: 600, color: "var(--fg1)" }}>{t("no_results")}</div><div style={{ fontSize: 14, marginTop: 4 }}>{t("no_results_hint")}</div>
              {(partners.length > 0 || cat !== "All categories") && (
                <div style={{ marginTop: 14 }}>
                  <Btn size="sm" variant="secondary" icon="x" onClick={() => { setPartners([]); setCat("All categories"); }}>{t("clear_all")}</Btn>
                </div>
              )}</Card>
            : <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 18 }}>
                {list.map(p => <ProductCard key={p.id} p={p} onOpen={onOpen} onAdd={onAdd} />)}
              </div>}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LoginScreen, CatalogueScreen, ProductCard });
