/* ============ CORE screens — family hub / shop (tenant-agnostic) ============ */

function InfoRow({ icon, k, v, muted }) {
  return (
    <div className="info-row">
      <span className="ir-ic"><Icon name={icon} size={17} /></span>
      <div style={{ flex: 1 }}>
        <div className="ir-k">{k}</div>
        <div className="ir-v" style={muted ? { color: "var(--muted)", fontStyle: "italic", fontWeight: 600 } : null}>{v}</div>
      </div>
    </div>
  );
}

function ChildCard({ child, onSetSchool, onShop, onResend }) {
  const C = useCatalog();
  const branding = useBranding();
  const campus = child.campusId ? C.campusById(child.campusId) : null;
  return (
    <div className="fam-card">
      <div className="fam-top">
        <Avatar name={child.name} size={50} seed={String(child.id).length} palette={branding.avatarPalette} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: "var(--hd)", fontWeight: 800, fontSize: 17 }}>{child.name}</div>
          <div style={{ marginTop: 4 }}>
            {child.claimed
              ? <Chip kind="ok" icon="check">Linked</Chip>
              : <Chip kind="neutral" icon="user">Added</Chip>}
          </div>
        </div>
      </div>
      <div className="fam-body">
        <InfoRow icon="campus" k="Campus" v={campus ? campus.name : "Not set"} muted={!campus} />
        <InfoRow icon="phone" k="Campus phone" v={campus && campus.phone ? campus.phone : "Not added"} muted={!campus || !campus.phone} />
      </div>
      <div className="fam-actions">
        <Btn kind="ghost" size="sm" icon="edit" onClick={onSetSchool}>Edit school</Btn>
        <Btn kind="primary" size="sm" icon="shop" onClick={onShop} style={{ marginLeft: "auto" }}>Shop</Btn>
      </div>
    </div>
  );
}

function FamilyHub({ role, me, children, onAddChild, onSetSchool, onShop, onResend, onEditMe, onShopMe }) {
  const user = useUser();
  if (role === "student") return <StudentSchoolInfo me={me} onEdit={onEditMe} onShop={onShopMe} />;

  const linked = children.filter((c) => c.status === "linked").length;
  const email = (user && user.email) || "you@email.com";
  return (
    <div className="wrap-wide screen-anim">
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16, flexWrap: "wrap", marginBottom: 6 }}>
        <div>
          <div className="eyebrow"><Icon name="parent" size={15} /> Account · My Family</div>
          <h1 className="h-title" style={{ fontSize: 32 }}>My Family</h1>
          <p className="h-sub" style={{ marginTop: 6 }}>{children.length} {children.length === 1 ? "child" : "children"} · {linked} linked · manage school and shopping.</p>
        </div>
        <Btn kind="primary" icon="plus" onClick={onAddChild}>Add a child</Btn>
      </div>

      <div className="fam-grid" style={{ gridTemplateColumns: "repeat(auto-fill,minmax(310px,1fr))", marginTop: 18 }}>
        {children.map((c) => (
          <ChildCard key={c.id} child={c}
            onSetSchool={() => onSetSchool(c.id)} onShop={() => onShop(c.id)} onResend={() => onResend(c.id)} />
        ))}
        <button className="add-tile" onClick={onAddChild}>
          <div className="role-ico" style={{ background: "#fff", border: "1px solid var(--line)" }}><Icon name="plus" size={24} /></div>
          <div style={{ fontFamily: "var(--hd)", fontWeight: 800, fontSize: 15 }}>Add another child</div>
          <div className="field-hint" style={{ marginTop: -4 }}>Add manually and assign a campus</div>
        </button>
      </div>

      <div className="card" style={{ marginTop: 22, padding: "20px 24px", display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
        <div className="role-ico" style={{ background: "var(--blue-050)", color: "var(--blue-600)" }}><Icon name="user" size={24} /></div>
        <div style={{ flex: 1, minWidth: 200 }}>
          <div style={{ fontFamily: "var(--hd)", fontWeight: 800, fontSize: 16 }}>Parent account</div>
          <div className="field-hint">{email} · Receives order updates for all linked children</div>
        </div>
        <Btn kind="outline" size="sm" icon="edit" onClick={onEditMe}>Edit account</Btn>
      </div>
    </div>
  );
}

function StudentSchoolInfo({ me, onEdit, onShop }) {
  const C = useCatalog();
  const campus = me.campusId ? C.campusById(me.campusId) : null;
  return (
    <div className="wrap screen-anim">
      <div className="eyebrow"><Icon name="grad" size={15} /> Account · School Info</div>
      <h1 className="h-title" style={{ fontSize: 32 }}>My School Info</h1>
      <p className="h-sub" style={{ marginTop: 6 }}>This is what we use to show your campus store.</p>

      <div className="card" style={{ marginTop: 20, overflow: "hidden" }}>
        {campus && (
          <div style={{ background: "var(--navy-800)", color: "#fff", padding: "22px 26px", display: "flex", gap: 16, alignItems: "center" }}>
            <div className="role-ico" style={{ background: "rgba(255,255,255,.15)", color: "#fff", width: 54, height: 54 }}><Icon name="campus" size={28} /></div>
            <div>
              <div style={{ fontSize: 12, letterSpacing: ".1em", textTransform: "uppercase", opacity: .8, fontWeight: 700 }}>My Campus</div>
              <div style={{ fontFamily: "var(--hd)", fontWeight: 800, fontSize: 21, marginTop: 2 }}>{campus.name}</div>
              {campus.address && <div style={{ opacity: .85, fontSize: 13.5, marginTop: 2 }}>{campus.address}</div>}
            </div>
          </div>
        )}
        <div style={{ padding: "8px 26px 6px" }}>
          <InfoRow icon="phone" k="Campus phone" v={campus && campus.phone ? campus.phone : "—"} />
        </div>
        <div className="fam-actions" style={{ padding: "16px 26px" }}>
          <Btn kind="ghost" icon="edit" onClick={onEdit}>Edit school info</Btn>
          <Btn kind="primary" icon="shop" onClick={onShop} style={{ marginLeft: "auto" }}>Shop my store</Btn>
        </div>
      </div>
    </div>
  );
}

/* ============ School map (OpenStreetMap embed) ============ */
function osmSrc(c) {
  const dy = 0.011, dx = 0.018;
  const bbox = [c.lng - dx, c.lat - dy, c.lng + dx, c.lat + dy].map((n) => n.toFixed(5)).join(",");
  return "https://www.openstreetmap.org/export/embed.html?bbox=" + bbox + "&layer=mapnik&marker=" + c.lat + "," + c.lng;
}
function SchoolMap({ campus }) {
  const C = useCatalog();
  const hasCoords = campus.lat != null && campus.lng != null;
  return (
    <div className="map-card">
      <div className="map-frame">
        {hasCoords ? (
          <iframe key={campus.id} title={"Map of " + campus.name} src={osmSrc(campus)} loading="lazy"></iframe>
        ) : (
          <div style={{ display: "grid", placeItems: "center", height: "100%", color: "var(--muted)", fontWeight: 600 }}>
            Map unavailable for this campus
          </div>
        )}
        {hasCoords && (
          <a className="map-open" target="_blank" rel="noreferrer"
            href={"https://www.openstreetmap.org/?mlat=" + campus.lat + "&mlon=" + campus.lng + "#map=15/" + campus.lat + "/" + campus.lng}>
            <Icon name="pin" size={13} /> View larger map
          </a>
        )}
      </div>
      <div className="map-info">
        <div className="role-ico" style={{ background: "var(--blue-050)", color: "var(--blue-600)", width: 46, height: 46 }}>
          <Icon name="campus" size={24} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: "var(--hd)", fontWeight: 800, fontSize: 17 }}>{campus.name}</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 5, marginTop: 7 }}>
            {campus.address && <span className="map-line"><Icon name="pin" size={15} />{campus.address}</span>}
            {campus.phone && <span className="map-line"><Icon name="phone" size={15} />{campus.phone}</span>}
            <span className="map-line"><Icon name="grad" size={15} />{[campus.levels, C.regionName(campus.region_slug) ? C.regionName(campus.region_slug) + " Region" : null].filter(Boolean).join(" · ")}</span>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============ Screen 5 — Shop for [child] / a school ============ */
function ShopFor({ children, initial, onBack, onContinue }) {
  const C = useCatalog();
  const copy = useCopy();
  const branding = useBranding();
  const shoppable = children.filter((c) => c.status === "linked" && c.campusId);
  const hasKids = shoppable.length > 0;
  const initSchool = typeof initial === "string" && initial.indexOf("school:") === 0;
  const firstCampusId = (C.campuses[0] && C.campuses[0].id) || null;
  const [mode, setMode] = React.useState(initSchool || !hasKids ? "school" : "child");
  const [sel, setSel] = React.useState((!initSchool && initial) || (shoppable[0] && shoppable[0].id) || null);
  const [schoolId, setSchoolId] = React.useState((initSchool && initial.slice(7)) || (shoppable[0] && shoppable[0].campusId) || firstCampusId);

  const selChild = shoppable.find((c) => c.id === sel);
  const childCampus = selChild && selChild.campusId ? C.campusById(selChild.campusId) : null;
  const school = C.campusById(schoolId);
  const campusOpts = C.campuses.map((c) => ({ value: c.id, label: c.name, sub: c.address, group: c.region_slug, icon: "campus" }));
  const campusGroups = C.regions.map((r) => ({ id: r.slug, label: r.name + " Region" }));

  const ctaCampus = mode === "child" ? childCampus : school;
  const canContinue = mode === "child" ? !!sel : !!schoolId;
  function cont() { onContinue(mode === "child" ? sel : "school:" + schoolId); }

  return (
    <div className="wrap screen-anim">
      <div className="card card-pad">
        <div className="eyebrow"><Icon name="shop" size={15} /> Start shopping</div>
        <h1 className="h-title">Who are you shopping for?</h1>
        <p className="h-sub">{copy.shopForSubtitle}</p>

        <div className="seg">
          <button className={mode === "child" ? "on" : ""} onClick={() => setMode("child")}><Icon name="parent" size={17} /> My children</button>
          <button className={mode === "school" ? "on" : ""} onClick={() => setMode("school")}><Icon name="campus" size={17} /> Another school</button>
        </div>

        {mode === "child" ? (
          <div style={{ marginTop: 18, display: "flex", flexDirection: "column", gap: 11 }}>
            {shoppable.map((c) => {
              const cam = C.campusById(c.campusId);
              const on = sel === c.id;
              return (
                <button key={c.id} className={"role-card" + (on ? " sel" : "")} style={{ alignItems: "center" }} onClick={() => setSel(c.id)}>
                  <Avatar name={c.name} size={48} seed={String(c.id).length} palette={branding.avatarPalette} />
                  <div style={{ flex: 1 }}>
                    <div className="role-name">{c.name}</div>
                    <div className="role-desc" style={{ display: "flex", alignItems: "center", gap: 6 }}>
                      <Icon name="campus" size={14} /> {cam ? cam.name : "Campus not set"}
                    </div>
                  </div>
                  <div className="role-check">{on && <Icon name="check" size={14} stroke={3} style={{ color: "#fff" }} />}</div>
                </button>
              );
            })}
            {!hasKids && (
              <Callout icon="info">No children are ready to shop for yet. Add a child from <b>My Family</b>, or switch to <b>Another school</b> to shop any campus.</Callout>
            )}
            {children.some((c) => c.status === "pending") && (
              <Callout icon="clock" warm>
                {children.filter((c) => c.status === "pending").length} pending child can’t be shopped for until they accept their invite.
              </Callout>
            )}
          </div>
        ) : (
          <div style={{ marginTop: 18 }}>
            <Field label="Choose a school" required hint="Search by school or region. The map updates as you switch schools.">
              <Combo value={schoolId} onChange={setSchoolId} options={campusOpts} groups={campusGroups} filled placeholder={copy.shopForPlaceholder} />
            </Field>
            {school && <SchoolMap campus={school} />}
          </div>
        )}

        <div className="divider" />
        <div className="row-between">
          <Btn kind="quiet" icon="chevLeft" onClick={onBack}>Back to family</Btn>
          <Btn kind="primary" disabled={!canContinue} iconR="arrowR" onClick={cont}>
            {ctaCampus ? "Continue to " + shortCampus(ctaCampus.name) : "Continue to store"}
          </Btn>
        </div>
      </div>
    </div>
  );
}
function shortCampus(n) { return n.length > 24 ? n.split(" ").slice(0, 3).join(" ") + "…" : n; }

/* ============ Store handoff ============ */
function handoffErrorText(message) {
  if (message === "role_required") return "Choose a role before continuing to the store.";
  if (message === "student_profile_required") return "Save your school info before continuing to the store.";
  if (message === "parent_child_required") return "Add a child before continuing to the store.";
  return "Store handoff is not ready: " + message;
}

function StoreLanding({ shoppingFor, onChange, onBackHub }) {
  const C = useCatalog();
  const copy = useCopy();
  const branding = useBranding();
  const tenant = useTenant();
  const api = useApi();
  const launch = useLaunchContext();
  const embedded = useEmbedded();
  const campus = shoppingFor && shoppingFor.campusId ? C.campusById(shoppingFor.campusId) : null;
  const handoff = campus ? window.buildCommerceHandoff(tenant.config.commerce, tenant.config.key, campus) : null;
  const studentId = shoppingFor && !shoppingFor.isSchool && shoppingFor.studentId != null ? shoppingFor.studentId : null;
  const [serverHandoff, setServerHandoff] = React.useState(null);
  const [handoffError, setHandoffError] = React.useState(null);
  const [redirectStarted, setRedirectStarted] = React.useState(false);
  const returnUrl = (launch && launch.returnUrl) || (handoff && handoff.url) || null;
  const handoffMode = (launch && launch.mode) || (embedded ? "iframe" : "redirect");
  React.useEffect(() => {
    if (!campus || !handoff || !returnUrl) return;

    let cancelled = false;
    setServerHandoff(null);
    setHandoffError(null);
    setRedirectStarted(false);

    api.returnContext({
      campusId: campus.id,
      campusRef: campus.external_ref || String(campus.id),
      returnUrl,
      studentId,
      mode: handoffMode
    }).then((res) => {
      if (cancelled) return;
      const next = res && res.handoff;
      if (!next) {
        setHandoffError("handoff_missing");
        return;
      }
      if (next && next.mode === "iframe" && next.postMessage && window.parent && window.parent !== window) {
        setServerHandoff(next);
        window.parent.postMessage(next.postMessage, next.postMessage.targetOrigin);
        return;
      }
      if (next.url) {
        setRedirectStarted(true);
        window.location.replace(next.url);
        return;
      }
      setServerHandoff(next);
      setHandoffError("handoff_url_missing");
    }).catch((e) => {
      if (!cancelled) setHandoffError((e && e.message) || "handoff_failed");
    });

    return () => { cancelled = true; };
  }, [api, campus && campus.id, campus && campus.external_ref, handoff && handoff.url, returnUrl, studentId, handoffMode]);
  const finalUrl = serverHandoff && serverHandoff.url ? serverHandoff.url : null;
  if (handoff) {
    const statusTitle = handoffError
      ? "Store redirect needs attention"
      : handoffMode === "iframe" && serverHandoff
        ? "Store context sent"
        : "Opening " + handoff.platformLabel + " store";
    const statusText = handoffError
      ? handoffErrorText(handoffError)
      : handoffMode === "iframe"
        ? "Sending the selected campus to the storefront."
        : redirectStarted
          ? "Redirecting now."
          : "Preparing the selected campus storefront.";

    return (
      <div className="wrap-wide screen-anim">
        <div className="card" style={{ padding: "22px", maxWidth: 680, margin: "0 auto" }}>
          <div className="row" style={{ gap: 14, alignItems: "flex-start" }}>
            <div className="role-ico" style={{ background: "var(--blue-050)", color: "var(--blue-600)", width: 42, height: 42 }}><Icon name={handoffError ? "info" : "shop"} size={22} /></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <h1 className="h-title" style={{ fontSize: 24, margin: 0 }}>{statusTitle}</h1>
              <p className="h-sub" style={{ marginTop: 6 }}>{statusText}</p>
              {campus && <div className="field-hint" style={{ marginTop: 10 }}>{campus.name}</div>}
              {handoffError && (
                <div className="row" style={{ marginTop: 18, gap: 10, flexWrap: "wrap" }}>
                  {finalUrl && <a className="btn btn-primary btn-sm" href={finalUrl}><Icon name="arrowR" size={16} /> Open store</a>}
                  <Btn kind="outline" size="sm" icon="campus" onClick={onChange}>Choose another campus</Btn>
                  <Btn kind="quiet" size="sm" onClick={onBackHub}>My Family</Btn>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    );
  }
  // Placeholder grid standing in for the live BigCommerce storefront; swatch colors are illustrative.
  const products = [
    { n: "Spirit Tee", p: "$14.00", c: "#1C6FE0" },
    { n: "Campus Hoodie", p: "$32.00", c: "#0A3A75" },
    { n: "Logo Water Bottle", p: "$11.50", c: "#E8821E" },
    { n: "Drawstring Bag", p: "$9.00", c: "#1E9E62" },
    { n: "Spirit Cap", p: "$16.00", c: "#7A4FD0" },
    { n: "Notebook Set", p: "$7.50", c: "#0E8FA8" },
  ];
  return (
    <div className="wrap-wide screen-anim">
      {shoppingFor && (
        <div className="card" style={{ padding: "16px 22px", display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap", marginBottom: 20, borderLeft: "5px solid var(--blue-600)" }}>
          {shoppingFor.isSchool ? (
            <div className="role-ico" style={{ background: "var(--blue-050)", color: "var(--blue-600)", width: 42, height: 42 }}><Icon name="campus" size={22} /></div>
          ) : (
            <Avatar name={shoppingFor.name} size={42} seed={String(shoppingFor.id || "").length} palette={branding.avatarPalette} />
          )}
          <div style={{ flex: 1, minWidth: 180 }}>
            <div className="field-hint" style={{ marginBottom: 1 }}>{shoppingFor.isSchool ? "You’re shopping the store for" : "You’re shopping for"}</div>
            <div style={{ fontFamily: "var(--hd)", fontWeight: 800, fontSize: 17 }}>
              {shoppingFor.isSchool
                ? (campus ? campus.name : "Campus store")
                : <>{shoppingFor.name} {campus && <span style={{ color: "var(--muted)", fontWeight: 700, fontSize: 14 }}>· {campus.name}</span>}</>}
            </div>
          </div>
          <Btn kind="outline" size="sm" icon={shoppingFor.isSchool ? "campus" : "parent"} onClick={onChange}>{shoppingFor.isSchool ? "Switch school" : "Switch child"}</Btn>
          <Btn kind="quiet" size="sm" onClick={onBackHub}>My Family</Btn>
        </div>
      )}

      <h1 className="h-title" style={{ fontSize: 28 }}>{campus ? campus.name : copy.storeFallbackName} Store</h1>
      <p className="h-sub" style={{ marginTop: 4 }}>Spirit wear, uniforms &amp; supplies — placeholder products standing in for the live {handoff ? handoff.platformLabel : "storefront"} catalog, which would be filtered to this campus.</p>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(200px,1fr))", gap: 16, marginTop: 22 }}>
        {products.map((pr) => (
          <div key={pr.n} className="fam-card" style={{ padding: 14 }}>
            <div style={{ height: 130, borderRadius: 12, background: pr.c + "1A", display: "grid", placeItems: "center", color: pr.c, marginBottom: 12 }}>
              <Icon name="shop" size={40} />
            </div>
            <div style={{ fontFamily: "var(--hd)", fontWeight: 800, fontSize: 15 }}>{pr.n}</div>
            <div className="row-between" style={{ marginTop: 6 }}>
              <span style={{ fontFamily: "var(--hd)", fontWeight: 800, color: "var(--blue-600)" }}>{pr.p}</span>
              <Btn kind="ghost" size="sm" icon="cart">Add</Btn>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { InfoRow, ChildCard, FamilyHub, StudentSchoolInfo, SchoolMap, ShopFor, StoreLanding, shortCampus });
