// App stage: full-screen mobile prototype, no nav chrome.

const TWEAKS = /*EDITMODE-BEGIN*/{
  "showScore": true,
  "accent": "coral",
  "showBeforeAfter": true
}/*EDITMODE-END*/;

const MOBILE_NAV_HEIGHT = 54;

const MOBILE_NAV_ITEMS = [
  { key: "home", label: "Home", icon: "nav-home.svg", type: "navigation", testId: "app-footer-home-menu-item" },
  { key: "jobs", label: "Jobs", icon: "nav-work.svg", type: "navigation", testId: "app-footer-jobs-menu-item" },
  { key: "headhunters", label: "Headhunters", icon: "nav-headhunters.svg", type: "navigation", testId: "app-footer-headhunters-menu-item" },
  { key: "resume", label: "Resume", icon: "nav-resume.svg", type: "bottomsheet", testId: "app-footer-resume-menu-item" },
  { key: "more", label: "More", icon: "nav-more.svg", type: "bottomsheet", testId: "app-footer-more-menu-item" },
];

const RESUME_SHEET_ITEMS = [
  { value: "resume_builder", label: "Resume builder" },
  { value: "free_review", label: "Free review" },
];

const MORE_SHEET_ITEMS = [
  { value: "master_class", label: "MasterClass", icon: "description.svg" },
];

function useResumeEditor() {
  const [issueStates, setIssueStates] = React.useState({});
  const [activeId, setActiveId] = React.useState(null);
  const [version, setVersion] = React.useState("v1");
  const [history, setHistory] = React.useState([]);

  const allIds = Object.keys(window.ISSUES);
  const openIssues = allIds.filter(id => issueStates[id]?.state !== "accepted" && issueStates[id]?.state !== "dismissed");
  const acceptedCount = allIds.filter(id => issueStates[id]?.state === "accepted").length;
  const dismissedCount = allIds.filter(id => issueStates[id]?.state === "dismissed").length;

  const base = 62;
  const score = Math.min(98, base + acceptedCount * 5 + dismissedCount * 1);

  const setStatesWithHistory = React.useCallback((updater) => {
    setIssueStates(prev => {
      const next = typeof updater === "function" ? updater(prev) : updater;
      setHistory(h => [...h, prev]);
      return next;
    });
  }, []);

  const undo = () => {
    setHistory(h => {
      if (h.length === 0) return h;
      const prev = h[h.length - 1];
      setIssueStates(prev);
      return h.slice(0, -1);
    });
  };

  const handleFixAll = () => {
    setStatesWithHistory(prev => {
      const next = { ...prev };
      openIssues.forEach(id => {
        next[id] = { state: "accepted", replaced: window.ISSUES[id].suggestion };
      });
      return next;
    });
    setActiveId(null);
  };

  return {
    issueStates, setIssueStates: setStatesWithHistory,
    activeId, setActiveId,
    version, setVersion,
    score, openIssues,
    handleFixAll, undo, canUndo: history.length > 0,
  };
}
window.useResumeEditor = useResumeEditor;

function MobileBottomSheet({ open, title, items, onClose, onItemClick, testId }) {
  if (!open) {
    return null;
  }

  return (
    <>
      <div
        onClick={onClose}
        style={{
          position: "fixed",
          inset: 0,
          background: "rgba(16,15,14,.28)",
          zIndex: 65,
        }}
      />
      <div
        style={{
          position: "fixed",
          left: 0,
          right: 0,
          bottom: "var(--mobile-nav-height, 54px)",
          zIndex: 70,
          background: "var(--color-neutral-100)",
          borderTopLeftRadius: 24,
          borderTopRightRadius: 24,
          boxShadow: "0 -8px 24px rgba(0,0,0,.08)",
          padding: "24px 16px calc(24px + var(--safe-bottom, 0px))",
        }}
      >
        <h3
          style={{
            margin: "0 0 12px",
            fontFamily: "var(--font-body)",
            fontSize: 18,
            fontWeight: 500,
            color: "var(--fg-1)",
          }}
        >
          {title}
        </h3>
        <ul
          data-testid={testId}
          style={{
            margin: 0,
            padding: 0,
            listStyle: "none",
            borderRadius: 12,
            border: "1px solid var(--border-1)",
            overflow: "hidden",
            background: "var(--color-neutral-99)",
          }}
        >
          {items.map((item, index) => (
            <li key={item.value}>
              <button
                onClick={() => onItemClick(item)}
                style={{
                  width: "100%",
                  display: "flex",
                  alignItems: "center",
                  gap: 10,
                  padding: "12px 14px",
                  border: 0,
                  borderTop: index === 0 ? "none" : "1px solid var(--border-1)",
                  background: "transparent",
                  color: "var(--fg-1)",
                  cursor: "pointer",
                  textAlign: "left",
                  fontFamily: "var(--font-body)",
                  fontSize: 14,
                  lineHeight: "20px",
                  fontWeight: 400,
                }}
              >
                {item.icon && <Icon name={item.icon} size={18} />}
                <span>{item.label}</span>
              </button>
            </li>
          ))}
        </ul>
      </div>
    </>
  );
}

function MobileBottomNavigation() {
  const [activeKey, setActiveKey] = React.useState("home");
  const [showResumeSheet, setShowResumeSheet] = React.useState(false);
  const [showMoreSheet, setShowMoreSheet] = React.useState(false);

  const closeAllSheets = React.useCallback(() => {
    setShowResumeSheet(false);
    setShowMoreSheet(false);
  }, []);

  const handleItemClick = React.useCallback((item) => {
    if (item.type === "navigation") {
      closeAllSheets();
      setActiveKey(item.key);
      return;
    }

    if (item.key === "resume") {
      if (showResumeSheet) {
        setShowResumeSheet(false);
      } else {
        setShowMoreSheet(false);
        setTimeout(() => setShowResumeSheet(true), 100);
      }
      return;
    }

    if (item.key === "more") {
      if (showMoreSheet) {
        setShowMoreSheet(false);
      } else {
        setShowResumeSheet(false);
        setTimeout(() => setShowMoreSheet(true), 100);
      }
    }
  }, [closeAllSheets, showMoreSheet, showResumeSheet]);

  const onKeyDown = (event, item) => {
    if (event.key === "Enter") {
      handleItemClick(item);
    }
  };

  return (
    <>
      <div
        className="app-header-menu-mobile"
        style={{
          position: "fixed",
          left: 0,
          right: 0,
          bottom: 0,
          padding: "8px 16px",
          zIndex: 60,
          background: "var(--color-neutral-0)",
          transition: "transform .3s ease-out",
        }}
      >
        <ul
          tabIndex={1}
          style={{
            margin: 0,
            padding: 0,
            listStyle: "none",
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
          }}
        >
          {MOBILE_NAV_ITEMS.map((item, index) => {
            const isActive = item.type === "navigation" ? item.key === activeKey : false;
            return (
              <li
                key={item.key}
                data-testid={item.testId}
                tabIndex={index + 1}
                onClick={() => handleItemClick(item)}
                onKeyDown={(event) => onKeyDown(event, item)}
                style={{
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                  cursor: "pointer",
                  opacity: isActive ? 1 : 0.6,
                  transition: "opacity .2s",
                  color: "var(--color-neutral-100)",
                  minWidth: 44,
                }}
              >
                <Icon name={item.icon} size={20} style={{ filter: "brightness(0) invert(1)" }} />
                <span
                  style={{
                    fontFamily: "var(--font-body)",
                    fontSize: 12,
                    lineHeight: "16px",
                    fontWeight: 500,
                    color: "var(--color-neutral-100)",
                  }}
                >
                  {item.label}
                </span>
              </li>
            );
          })}
        </ul>
      </div>

      <MobileBottomSheet
        open={showResumeSheet}
        title="Resume"
        items={RESUME_SHEET_ITEMS}
        testId="app-footer-resume-sheet"
        onClose={() => setShowResumeSheet(false)}
        onItemClick={() => setShowResumeSheet(false)}
      />

      <MobileBottomSheet
        open={showMoreSheet}
        title="More services"
        items={MORE_SHEET_ITEMS}
        testId="app-footer-more-sheet"
        onClose={() => setShowMoreSheet(false)}
        onItemClick={() => setShowMoreSheet(false)}
      />
    </>
  );
}

function Stage() {
  const [tweaks, setTweaks] = React.useState(TWEAKS);
  const [tweaksOpen, setTweaksOpen] = React.useState(false);
  const [fixAllPulse, setFixAllPulse] = React.useState(false);

  const ctx = useResumeEditor();

  const wrappedFixAll = () => {
    ctx.handleFixAll();
    setFixAllPulse(true);
    setTimeout(() => setFixAllPulse(false), 700);
  };
  const liveCtx = { ...ctx, handleFixAll: wrappedFixAll };

  React.useEffect(() => {
    const handler = (e) => {
      if (e.data?.type === "__activate_edit_mode") setTweaksOpen(true);
      if (e.data?.type === "__deactivate_edit_mode") setTweaksOpen(false);
    };
    window.addEventListener("message", handler);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", handler);
  }, []);

  React.useEffect(() => {
    const syncViewportVars = () => {
      const vv = window.visualViewport;
      const appHeight = vv ? vv.height : window.innerHeight;
      document.documentElement.style.setProperty("--app-height", `${Math.round(appHeight)}px`);
    };

    syncViewportVars();
    window.addEventListener("resize", syncViewportVars);
    window.addEventListener("orientationchange", syncViewportVars);
    window.visualViewport?.addEventListener("resize", syncViewportVars);
    window.visualViewport?.addEventListener("scroll", syncViewportVars);

    return () => {
      window.removeEventListener("resize", syncViewportVars);
      window.removeEventListener("orientationchange", syncViewportVars);
      window.visualViewport?.removeEventListener("resize", syncViewportVars);
      window.visualViewport?.removeEventListener("scroll", syncViewportVars);
    };
  }, []);

  const updateTweak = (k, v) => {
    const next = { ...tweaks, [k]: v };
    setTweaks(next);
    window.parent.postMessage({ type: "__edit_mode_set_keys", edits: { [k]: v } }, "*");
  };

  const accentMap = { coral: "var(--color-primary-base)", lime: "var(--color-secondary-base)", indigo: "var(--color-ai-50)" };

  return (
    <div style={{
      width: "100vw",
      height: "var(--app-height, 100vh)",
      overflow: "hidden",
      position: "relative",
      fontFamily: "var(--font-body)",
      "--mobile-nav-height": `${MOBILE_NAV_HEIGHT}px`,
    }}>
      <style>{`
        .pulse::after {
          content: ""; position: absolute; inset: 0;
          background: radial-gradient(circle at 50% 0%, rgba(232,255,99,.55), transparent 70%);
          pointer-events: none; animation: pulseFade .7s ease-out forwards;
        }
        @keyframes pulseFade {
          0%   { opacity: 0; }
          40%  { opacity: 1; }
          100% { opacity: 0; }
        }
      `}</style>

      <div style={{ width: "100%", height: "100%", position: "relative" }} className={fixAllPulse ? "pulse" : ""}>
        <VariantSheet ctx={liveCtx} />
      </div>

      <MobileBottomNavigation />

      {/* Tweaks panel (edit mode only) */}
      {tweaksOpen && (
        <div style={{
          position: "fixed", right: 16, bottom: 16, width: 256,
          background: "var(--color-neutral-100)", border: "1px solid var(--border-1)",
          borderRadius: 16, padding: 16, boxShadow: "var(--shadow-xl)", zIndex: 200,
          fontFamily: "var(--font-body)",
        }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
            <div style={{ fontFamily: "var(--font-heading)", fontWeight: 500, fontSize: 16, letterSpacing: "-.01em" }}>Tweaks</div>
            <button onClick={() => setTweaksOpen(false)} style={{ background: "transparent", border: 0, cursor: "pointer", padding: 4, display: "inline-flex" }}>
              <Icon name="close.svg" size={14} />
            </button>
          </div>

          <TweakLabel>Accent</TweakLabel>
          <div style={{ display: "flex", gap: 6, marginBottom: 14 }}>
            {["coral","lime","indigo"].map(a => (
              <button key={a} onClick={() => updateTweak("accent", a)} style={{
                width: 32, height: 32, borderRadius: 999,
                border: tweaks.accent === a ? "2.5px solid var(--color-neutral-0)" : "2px solid var(--border-1)",
                background: accentMap[a], cursor: "pointer",
              }} title={a}/>
            ))}
          </div>

          <label style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "8px 0", cursor: "pointer" }}>
            <span style={{ fontSize: 13 }}>Show score ring</span>
            <input type="checkbox" checked={tweaks.showScore} onChange={e => updateTweak("showScore", e.target.checked)}/>
          </label>

          <button onClick={() => { ctx.handleFixAll(); }} style={{
            marginTop: 6, width: "100%", background: "var(--color-neutral-0)", color: "var(--color-neutral-100)",
            border: 0, padding: "10px 14px", borderRadius: 999, cursor: "pointer",
            fontFamily: "var(--font-body)", fontSize: 13, fontWeight: 500,
            display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6,
          }}>
            <span style={{color:"var(--color-secondary-base)",display:"inline-flex"}}><Icon name="sparkle.svg" size={12}/></span>
            Run "Fix all" demo
          </button>
        </div>
      )}
    </div>
  );
}

function TweakLabel({ children }) {
  return <div style={{ fontSize: 10, letterSpacing: ".12em", textTransform: "uppercase", color: "var(--fg-3)", marginBottom: 6, fontWeight: 500 }}>{children}</div>;
}

window.Stage = Stage;
ReactDOM.createRoot(document.getElementById("root")).render(<Stage/>);
