/* global React */
(function(){

/* =============================================================
   Shell.jsx — app shell with topnav (desktop) + bumped bottomnav
   (mobile) + a radial content-composer that fans out of the + FAB.
   ============================================================= */

const NAV_ITEMS = [
  { id: "home",    label: "خانه",      icon: "home" },
  { id: "explore", label: "کاوش",      icon: "target" },
  { id: "reward",  label: "پاداش‌ها",  icon: "trophy" },
  { id: "profile", label: "پروفایل",   icon: "profile" },
];

/* radial composer — left→right above the FAB (RTL: سوال … متن) */
const COMPOSE_TYPES = [
  { id:"question", label:"سوال",   icon:"question", color:"#4be3ff", angle:150 },
  { id:"image",    label:"تصویر",  icon:"image",    color:"#ff8a3d", angle:120 },
  { id:"video",    label:"ویدیو",  icon:"video",    color:"#ff4ea8", angle:90  },
  { id:"audio",    label:"صوت",    icon:"audio",    color:"#44e3b8", angle:60  },
  { id:"text",     label:"متن",    icon:"text",     color:"#9a6cff", angle:30  },
];
const RADIAL_R = 132;

/* ----- bumped bar background, sized to the viewport so the bump
   stays circular at any phone width. We compute the SVG path live. -- */
function BumpedBarBg() {
  const [w, setW] = React.useState(() =>
    typeof window === "undefined" ? 390 : Math.min(window.innerWidth, 720));
  React.useEffect(() => {
    const onR = () => setW(Math.min(window.innerWidth, 720));
    onR();
    window.addEventListener("resize", onR);
    return () => window.removeEventListener("resize", onR);
  }, []);
  // SVG coords: total 118 tall; bar flat top sits at y = 44.
  const H = 22, TOTAL = 96;
  const cx = w / 2;
  const R = 30;            // bump radius (a clean circular arc)
  const fillet = 10;       // smooth tangent fillet between flat bar & bump
  // Path: run in along the flat top, ease up into a half-circle arc,
  // ease back down to the flat top. The arc uses A with sweep=0 (upward).
  const path =
    `M 0 ${H} ` +
    `L ${cx - R - fillet} ${H} ` +
    'a 20.27 20.27 0 0 0 13.5 -8 ' +
    'a 33 33 0 0 1 53 0 ' +
    'a 20.27 20.27 0 0 0 13.5 8 ' +
    `L ${w} ${H} L ${w} ${TOTAL} L 0 ${TOTAL} Z`;
  return (
    <React.Fragment>
      <div
        className="kd-bumpbar__fill"
        style={{
          clipPath: `path("${path}")`,
          WebkitClipPath: `path("${path}")`,
        }}
      />
      <svg
        className="kd-bumpbar__stroke"
        viewBox={`0 0 ${w} ${TOTAL}`}
        width="100%"
        height={TOTAL}
        preserveAspectRatio="none"
        aria-hidden="true"
      >
        <path
          d={path}
          fill="none"
          stroke="rgba(255,255,255,.14)"
          strokeWidth="1"
          vectorEffect="non-scaling-stroke"
        />
      </svg>
    </React.Fragment>
  );
}

window.Shell = function Shell({ route, onRoute, onUpload, dark, signedIn, children }) {
  const [composerOpen, setComposerOpen] = React.useState(false);

  // Esc closes the composer
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape" && composerOpen) setComposerOpen(false); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [composerOpen]);

  const pickType = (type) => {
    setComposerOpen(false);
    // متن و سوال هر دو می‌رن به افزودن متن — pass the chosen content type
    // so the host can open UploadWizard with the picker skipped.
    const mapped = type.id === "question" ? "text" : type.id;
    window.dispatchEvent(new CustomEvent("kd-compose-type", { detail: { type: mapped } }));
    onUpload?.(mapped);
  };

  return (
    <div className={`kd-shell ${dark ? "kd-dark" : ""}`}>
      <header className="kd-topnav">
        <div className="kd-topnav__inner">
          <a className="kd-logo" onClick={() => onRoute("home")}>
            <img src="../../assets/logo-512.png" alt="کشوردوست" />
            <span className="kd-logo__text">کشوردوست</span>
          </a>
          <nav className="kd-topnav__nav">
            {NAV_ITEMS.map(it => (
              <button
                key={it.id}
                className={`kd-topnav__item ${route === it.id ? "is-active" : ""}`}
                onClick={() => onRoute(it.id)}
              >
                <Icon name={it.icon} size={18} />
                <span>{it.label}</span>
              </button>
            ))}
          </nav>
          <div className="kd-topnav__right">
            <IconBtn title="جستجو" onClick={() => onRoute("search")}><Icon name="search" size={18} /></IconBtn>
            <IconBtn title="اعلان‌ها" onClick={() => onRoute("notifications")}>
              <Icon name="bell" size={18} />
              <span className="kd-iconbtn__dot" />
            </IconBtn>
            {signedIn ? (
              <Avatar name="مهسا" size={32} />
            ) : (
              <button
                className="kd-topnav__login"
                onClick={() => onRoute("login")}
                title="ورود"
              >
                ورود
              </button>
            )}
          </div>
        </div>
      </header>

      <main className="kd-main">{children}</main>

      {/* Desktop-only FAB pill — unchanged behavior */}
      <button className="kd-fab kd-fab--desktop" onClick={onUpload} aria-label="ارسال محتوا">
        <Icon name="plus" size={20} stroke={2.4} />
        <span className="kd-fab__label">بفرست</span>
      </button>

      {/* ============ Mobile composer system ============ */}
      <div className={`kd-compose ${composerOpen ? "is-open" : ""}`}>
        <div className="kd-compose__scrim" onClick={() => setComposerOpen(false)} />

        {/* glass dome — the "circle around the +" that grows on open */}
        <div className="kd-compose__dome" />

        {/* radial content-type buttons (icon + label, no chrome) */}
        <div className="kd-compose__radial" aria-hidden={!composerOpen}>
          {COMPOSE_TYPES.map((t, i) => {
            const rad = t.angle * Math.PI / 180;
            const tx = Math.cos(rad) * RADIAL_R;
            const ty = -Math.sin(rad) * RADIAL_R;
            return (
              <button
                key={t.id}
                className="kd-compose__item"
                style={{
                  "--tx": `${tx.toFixed(1)}px`,
                  "--ty": `${ty.toFixed(1)}px`,
                  "--c": t.color,
                  "--d-open": `${60 + i * 40}ms`,
                  "--d-close": `${(COMPOSE_TYPES.length - 1 - i) * 22}ms`,
                }}
                onClick={() => pickType(t)}
                tabIndex={composerOpen ? 0 : -1}
              >
                <span className="kd-compose__ic"><Icon name={t.icon} size={34} stroke={1.8} /></span>
                <span className="kd-compose__lbl">{t.label}</span>
              </button>
            );
          })}
        </div>

        {/* bumped bottom nav — the bar's background bulges around the + */}
        <nav className="kd-bumpbar" aria-label="ناوبری">
          <BumpedBarBg />
          <div className="kd-bumpbar__row">
            {NAV_ITEMS.slice(0, 2).map(it => (
              <button
                key={it.id}
                className={`kd-bumpbar__item ${route === it.id ? "is-active" : ""}`}
                onClick={() => onRoute(it.id)}
              >
                <span className="kd-bumpbar__icon"><Icon name={it.icon} size={22} /></span>
                <span className="kd-bumpbar__lbl">{it.label}</span>
              </button>
            ))}
            <span className="kd-bumpbar__item" aria-hidden="true">
	      <span class="kd-bumpbar__icon"></span>
	      <span class="kd-bumpbar__lbl">جدید</span>
            </span>
            {NAV_ITEMS.slice(2).map(it => (
              <button
                key={it.id}
                className={`kd-bumpbar__item ${route === it.id ? "is-active" : ""}`}
                onClick={() => onRoute(it.id)}
              >
                <span className="kd-bumpbar__icon"><Icon name={it.icon} size={22} /></span>
                <span className="kd-bumpbar__lbl">{it.label}</span>
              </button>
            ))}
          </div>
        </nav>

        {/* the + button — no background; sits in the bar's bump.
            A thin ring + a small inner glow read it as a raised seat. */}
        <button
          className="kd-compose__plus"
          onClick={() => setComposerOpen(v => !v)}
          aria-label={composerOpen ? "بستن" : "ساخت محتوای جدید"}
          aria-expanded={composerOpen}
        >
          <span className="kd-compose__plus-ring" aria-hidden="true" />
          <svg
            className="kd-compose__plus-ic"
            width="30" height="30" viewBox="0 0 24 24"
            fill="none" stroke="currentColor" strokeWidth="2.6"
            strokeLinecap="round"
          >
            <path d="M12 5v14"/>
            <path d="M5 12h14"/>
          </svg>
        </button>
      </div>
    </div>
  );
};
})();
