// Inlinr — App shell. Primary nav + view switching.
// Depends on: components in editor-components.jsx (Icon, Button, IconBtn, TopBar, LeftRail,
//             BlocksPanel, LayersPanel, LocalesPanel, Inspector, StatusBar, FloatingToolbar)
//             and on editor-blocks.jsx (renderBlock)
//             and on DashboardView, LocalizationView, MediaView, ShareModal.

const { useState, useMemo, useEffect, useRef } = React;

const VIEW_ROUTES = {
  dashboard: "/library",
  editor: "/composer",
  localization: "/locales",
  media: "/media",
  team: "/team-members",
};

const normalizePath = (path) => {
  if (!path) return "/";
  const normalized = path.replace(/\/+$/, "");
  return normalized || "/";
};

const resolveViewFromPath = (path) => {
  const normalized = normalizePath(path);
  if (normalized === "/") return "dashboard";
  const match = Object.entries(VIEW_ROUTES).find(([, route]) => route === normalized);
  return match?.[0] || "dashboard";
};

const isKnownViewPath = (path) => {
  const normalized = normalizePath(path);
  return normalized === "/" || Object.values(VIEW_ROUTES).includes(normalized);
};

const syncRouteForView = (view, replace = false) => {
  const route = VIEW_ROUTES[view] || VIEW_ROUTES.dashboard;
  if (normalizePath(window.location.pathname) === route) return;
  window.history[replace ? "replaceState" : "pushState"]({}, "", route);
};

const getAuthorizedView = (profile, requestedView) => (
  canAccessView(profile, requestedView) ? requestedView : getDefaultViewForProfile(profile)
);

/* ============================================================
   PRIMARY NAV (left rail, 76px)
   ============================================================ */
const PrimaryNav = ({ view, onNavigate, badges, onSignOut, profile }) => {
  const items = [
    { id: "dashboard",    icon: "grid",    label: "Library" },
    { id: "editor",       icon: "type",    label: "Composer" },
    { id: "localization", icon: "globe",   label: "Locales", badge: badges?.loc },
    { id: "media",        icon: "image",   label: "Media" },
    { id: "team",         icon: "users",   label: "Team" },
  ].filter(item => canAccessView(profile, item.id));
  return (
    <nav className="nav">
      <div className="nav-brand" title="Inlinr">
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" aria-hidden>
          <rect x="4" y="6"  width="14" height="2.4" rx="1.2" fill="#fff"/>
          <rect x="4" y="11" width="9"  height="2.4" rx="1.2" fill="#fff" opacity="0.55"/>
          <rect x="4" y="16" width="12" height="2.4" rx="1.2" fill="#fff" opacity="0.30"/>
        </svg>
      </div>
      <div className="nav-sep" />
      {items.map(it => (
        <button key={it.id}
          className={`nav-item${view === it.id ? " is-active" : ""}`}
          onClick={() => onNavigate(it.id)}
          title={it.label}>
          <Icon name={it.icon} size={18} />
          <span>{it.label}</span>
          {it.badge && <span className="badge">{it.badge}</span>}
        </button>
      ))}
      <div className="nav-spacer" />
      <button className="nav-item" title="Notifications">
        <Icon name="bell" size={18} />
      </button>
      <button className="nav-item" title="Settings">
        <Icon name="settings" size={18} />
      </button>
      <button className="nav-avatar" title={`${profile?.displayName || "User"} — click to sign out`}
        style={profile?.avatarColor ? {background: profile.avatarColor} : undefined}
        onClick={onSignOut}>{profile?.avatarInitials || "?"}</button>
    </nav>
  );
};

/* ============================================================
   EDITOR VIEW — wraps the kit IDE so it fills the main pane
   ============================================================ */
const SEED_BLOCKS = [
  { id: "b1", type: "hero",    icon: "image",   label: "Hero",      locales: "EN · FR · DE · ES", heading: "You're on the Pro plan." },
  { id: "b2", type: "text",    icon: "type",    label: "Text",      locales: "EN · FR · DE · ES" },
  { id: "b3", type: "columns", icon: "columns", label: "3 columns", locales: "EN · FR · DE" },
  { id: "b4", type: "cta",     icon: "button",  label: "CTA",       locales: "EN · FR · DE · ES" },
  { id: "b5", type: "divider", icon: "divider", label: "Divider",   locales: "—" },
  { id: "b6", type: "footer",  icon: "mail",    label: "Footer",    locales: "EN · FR · DE · ES" },
];

const EDITOR_LOCALES = [
  { code: "en", name: "English (en-US)", progress: 100 },
  { code: "fr", name: "Français (fr-FR)", progress: 96 },
  { code: "de", name: "Deutsch (de-DE)",  progress: 88 },
  { code: "es", name: "Español (es-ES)",  progress: 72, warn: "2 blocks missing copy" },
];

const EditorView = ({ onOpenShare }) => {
  const [tab, setTab] = useState("blocks");
  const [theme, setTheme] = useState("light");
  const [locale, setLocale] = useState("en");
  const [blocks] = useState(SEED_BLOCKS);
  const [selectedId, setSelectedId] = useState("b1");
  const [exportFlash, setExportFlash] = useState(false);
  const [device, setDevice] = useState("desktop");
  const [panelCollapsed, setPanelCollapsed] = useState(false);
  const [inspectorCollapsed, setInspectorCollapsed] = useState(false);

  const selected = useMemo(() => blocks.find(b => b.id === selectedId), [blocks, selectedId]);
  const currentLocale = useMemo(() => EDITOR_LOCALES.find(l => l.code === locale), [locale]);

  const handleExport = () => {
    setExportFlash(true);
    setTimeout(() => setExportFlash(false), 2200);
  };

  const sidePanel = {
    blocks:  <BlocksPanel />,
    layers:  <LayersPanel blocks={blocks} selectedId={selectedId} onSelect={setSelectedId} />,
    locales: <LocalesPanel locales={EDITOR_LOCALES} active={locale} onSelect={setLocale} />,
    media:   (
      <div className="side-panel">
        <div className="panel-head"><div className="panel-title">Media</div></div>
        <div className="panel-empty">Drag images here or paste from clipboard.</div>
      </div>
    ),
    settings: (
      <div className="side-panel">
        <div className="panel-head"><div className="panel-title">Settings</div></div>
        <div className="panel-empty">Editor preferences, keyboard shortcuts, export defaults.</div>
      </div>
    ),
  }[tab];

  return (
    <div className="ide">
      <TopBar
        docName="Welcome — Pro plan"
        locale={locale}
        locales={EDITOR_LOCALES}
        onLocaleChange={setLocale}
        theme={theme}
        setTheme={setTheme}
        onExport={handleExport}
        device={device}
        setDevice={setDevice}
      />

      <div className={`ide-body${panelCollapsed ? " panel-collapsed" : ""}${inspectorCollapsed ? " inspector-collapsed" : ""}`}>
        <LeftRail tab={tab} setTab={setTab}
          collapsed={panelCollapsed}
          onToggleCollapse={() => setPanelCollapsed(c => !c)} />
        {panelCollapsed ? <div className="side-panel-stub" /> : sidePanel}

        <div className="canvas-wrap" data-device={device}>
          {selected && (
            <div className="canvas-toolbar-mount">
              <FloatingToolbar />
            </div>
          )}

          <div className={`canvas${theme === "dark" ? " is-dark" : ""} device-${device}`} onClick={() => setSelectedId(null)}>
            <div className="canvas-meta">
              <span><Icon name="mail" size={12} /> From <b>brand@inlinr.com</b></span>
              <span>·</span>
              <span>To <b>you@example.com</b></span>
              <span>·</span>
              <span>Locale <b>{currentLocale.name}</b></span>
              {currentLocale.warn && (
                <span className="canvas-meta-warn">
                  <Icon name="warn" size={11} /> {currentLocale.warn}
                </span>
              )}
            </div>

            <div className="email-frame">
              <div className="email-subject">
                <div className="es-label">Subject</div>
                <div className="es-value">Welcome to your Pro plan</div>
                <div className="es-label">Preview</div>
                <div className="es-value es-preview">Everything you need to know about your new workspace …</div>
              </div>

              <div className="email-body">
                {blocks.map(b => renderBlock(b, {
                  selected: selectedId === b.id,
                  onSelect: setSelectedId,
                  theme,
                }))}
                <button className="add-block-row">
                  <Icon name="plus" size={12} />
                  <span>Add block</span>
                </button>
              </div>
            </div>
          </div>
        </div>

        <Inspector block={selected}
          collapsed={inspectorCollapsed}
          onToggleCollapse={() => setInspectorCollapsed(c => !c)} />
      </div>

      <StatusBar blocks={blocks} locale={locale} locales={EDITOR_LOCALES} theme={theme} />

      <div className={`toast${exportFlash ? " is-visible" : ""}`}>
        <span className="toast-spinner" />
        <span className="toast-text">Inlining CSS · bundling assets · packaging ZIP</span>
        <span className="toast-meta">welcome-pro.zip · 612 KB</span>
      </div>
    </div>
  );
};

/* ============================================================
   ROOT APP
   ============================================================ */
const App = () => {
  const [user, setUser] = useState(undefined);
  const [profile, setProfile] = useState(null);
  const [view, setView] = useState(() => resolveViewFromPath(window.location.pathname));
  const [shareOpen, setShareOpen] = useState(false);

  useEffect(() => {
    const onPopState = () => setView(resolveViewFromPath(window.location.pathname));
    window.addEventListener("popstate", onPopState);
    return () => window.removeEventListener("popstate", onPopState);
  }, []);

  useEffect(() => {
    return fbAuth.onAuthStateChanged(async (u) => {
      if (u) {
        try {
          const p = await ensureUserProfile(u);
          const nextView = getAuthorizedView(p, resolveViewFromPath(window.location.pathname));
          setProfile(p);
          setView(nextView);
          if (!isKnownViewPath(window.location.pathname) || normalizePath(window.location.pathname) === "/" || nextView !== resolveViewFromPath(window.location.pathname)) {
            syncRouteForView(nextView, true);
          }
        } catch (err) {
          console.error("Unable to initialize user profile", err);
          await fbAuth.signOut();
        }
      } else {
        setProfile(null);
      }
      setUser(u);
    });
  }, []);

  useEffect(() => {
    if (!user?.uid) return undefined;
    return fbDb.collection("users").doc(user.uid).onSnapshot((snap) => {
      if (!snap.exists) return;
      const nextProfile = { id: snap.id, ...snap.data() };
      setProfile(nextProfile);
      setView(currentView => {
        const authorizedView = getAuthorizedView(nextProfile, currentView);
        if (authorizedView !== currentView) {
          syncRouteForView(authorizedView, true);
        }
        return authorizedView;
      });
    });
  }, [user?.uid]);

  const navigateToView = (nextView, replace = false) => {
    const authorizedView = getAuthorizedView(profile, nextView);
    setView(authorizedView);
    syncRouteForView(authorizedView, replace);
  };

  const openCampaign = () => navigateToView("editor");
  const openShare = () => setShareOpen(true);

  if (user === undefined) {
    return <div className="auth" style={{display:"flex",alignItems:"center",justifyContent:"center"}}><span className="auth-spinner" /></div>;
  }

  if (!user) {
    return <LoginView onSignIn={() => {}} />;
  }

  return (
    <div className="app-shell">
      <PrimaryNav view={view} onNavigate={navigateToView} badges={{ loc: 12 }} onSignOut={() => fbAuth.signOut()} profile={profile} />

      <main className="main">
        {view === "dashboard" && (
          <DashboardView onOpenCampaign={openCampaign} onOpenShare={openShare} profile={profile} />
        )}
        {view === "editor" && (
          <EditorView onOpenShare={openShare} />
        )}
        {view === "localization" && <LocalizationView profile={profile} />}
        {view === "media" && <MediaView profile={profile} />}
        {view === "team" && <TeamView profile={profile} />}
      </main>

      <ShareModal open={shareOpen} onClose={() => setShareOpen(false)} />
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
