// BetyChef Founder Console — App root

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#06D001",
  "theme": "light",
  "density": "regular",
  "headingFont": "Bricolage Grotesque",
  "radius": 18
}/*EDITMODE-END*/;

const ACCENTS = {
  "#06D001":"BetyGreen","#059212":"Deep herb",
  "#9BEC00":"Lime","#10B981":"Emerald","#22C55E":"Fresh",
};
// Muted dark-mode counterpart for each accent swatch — neon green that pops
// on white paper turns into a glowing, eye-straining color on near-black.
// Same hue family, lower saturation/brightness so it stays calm at night.
const ACCENTS_DARK = {
  "#06D001":"#3FAE46", "#059212":"#3CB44B",
  "#9BEC00":"#A9C24A", "#10B981":"#1FA774", "#22C55E":"#34B85F",
};
const HEAD_FONTS = ["Bricolage Grotesque","Hanken Grotesk","Space Grotesk"];

function LoginScreen() {
  const [email,   setEmail]   = React.useState("");
  const [pass,    setPass]    = React.useState("");
  const [err,     setErr]     = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [showPass, setShowPass] = React.useState(false);

  async function submit(e) {
    e.preventDefault(); setErr(""); setLoading(true);
    try { await firebase.auth().signInWithEmailAndPassword(email, pass); }
    catch(e) { setErr(e.message); }
    setLoading(false);
  }

  return (
    <div className="bc-login-wrap">
      <div className="bc-login-card">
        <div className="bc-login-brand">
          <div className="bc-brand-mark" style={{width:52,height:52,borderRadius:16}}>
            <img src="assets/logo.jpg" alt="BetyChef"/>
          </div>
          <div>
            <div className="bc-brand-name" style={{fontSize:22}}>BetyChef</div>
            <div className="bc-brand-sub">Founder Console</div>
          </div>
        </div>
        <form onSubmit={submit} className="bc-login-form">
          <label className="bc-field">
            <span className="bc-field-label">Email</span>
            <input className="bc-input" type="email" value={email}
              onChange={e=>setEmail(e.target.value)} placeholder="you@betychef.com" required autoFocus/>
          </label>
          <label className="bc-field">
            <span className="bc-field-label">Password</span>
            <div style={{position:"relative"}}>
              <input className="bc-input" type={showPass?"text":"password"} value={pass}
                onChange={e=>setPass(e.target.value)} placeholder="••••••••" required
                style={{paddingRight:42}}/>
              <button type="button" onClick={()=>setShowPass(v=>!v)}
                style={{position:"absolute",right:12,top:"50%",transform:"translateY(-50%)",
                  background:"none",border:"none",cursor:"pointer",padding:0,
                  color:"var(--c-ink-2)",display:"flex",alignItems:"center"}}>
                <Icon name={showPass?"eye-off":"eye"} size={18}/>
              </button>
            </div>
          </label>
          {err && <div className="bc-login-err">{err}</div>}
          <button className="bc-btn bc-btn--primary bc-btn--full" type="submit" disabled={loading}>
            {loading?"Signing in…":"Sign in"}
          </button>
        </form>
      </div>
    </div>
  );
}

function LoadingScreen() {
  return (
    <div className="bc-login-wrap">
      <div style={{textAlign:"center",color:"var(--c-ink-2)"}}>
        <div className="bc-brand-mark" style={{width:52,height:52,borderRadius:16,margin:"0 auto 18px"}}>
          <img src="assets/logo.jpg" alt="BetyChef"/>
        </div>
        <div style={{fontFamily:"var(--font-head)",fontWeight:700,fontSize:18,color:"var(--c-ink)"}}>
          Loading live data…
        </div>
        <div style={{fontSize:13,marginTop:6}}>Connecting to Firebase</div>
        <div className="bc-pulse" style={{margin:"18px auto 0",width:10,height:10}}/>
      </div>
    </div>
  );
}

function App() {
  const [t, setTweak]       = useTweaks(TWEAK_DEFAULTS);
  const [view, setView]     = React.useState("overview");
  const [query, setQuery]   = React.useState("");
  const [authState, setAuth] = React.useState("checking");
  const [tick, setTick]     = React.useState(0);
  const [bcLoading, setBCLoading] = React.useState(true);
  const [sidebarMinimized, setSidebarMinimized] = React.useState(false);

  // navigate(viewId, filter?) — called from KPI cards etc.
  function navigate(viewId, _filter) {
    setView(viewId);
    window.scrollTo(0,0);
  }

  // Applied theme = the real, persistent toggle (window.BC_theme), not the
  // edit-mode Tweaks default — so light/dark works on the live dashboard too.
  const [theme, setThemeTick] = React.useState(() => window.BC_theme ? window.BC_theme.get() : t.theme);
  React.useEffect(() => {
    const sync = () => setThemeTick(window.BC_theme.get());
    window.addEventListener("themeChanged", sync);
    return () => window.removeEventListener("themeChanged", sync);
  }, []);

  React.useEffect(() => {
    const r = document.documentElement;
    // In dark mode, swap to the muted counterpart of the chosen accent —
    // the neon swatches are tuned for white paper and glow/strain on black.
    const appliedAccent = theme === "dark" ? (ACCENTS_DARK[t.accent] || t.accent) : t.accent;
    r.style.setProperty("--c-primary", appliedAccent);
    r.style.setProperty("--c-primary-text", theme==="dark"?"#5FCB68":"#059212");
    r.dataset.theme   = theme;
    r.dataset.density = t.density;
    r.style.setProperty("--radius",    t.radius+"px");
    r.style.setProperty("--font-head", `"${t.headingFont}", sans-serif`);
  }, [t, theme]);

  React.useEffect(() => {
    const unsub = firebase.auth().onAuthStateChanged(user => {
      if (user) {
        setAuth("loggedIn");
        window.BC_init(() => { setBCLoading(false); setTick(n=>n+1); });
      } else {
        setAuth("loggedOut");
      }
    });
    return unsub;
  }, []);

  if (authState === "checking")  return <LoadingScreen/>;
  if (authState === "loggedOut") return <LoginScreen/>;
  if (bcLoading)                 return <LoadingScreen/>;

  const Views = {
    overview:  <OverviewView  key={"ov"+tick}  navigate={navigate} />,
    chefs:        <ChefsView        key={"ch"+tick} query={query} navigate={navigate} />,
    applications: <ApplicationsView key={"ap"+tick} query={query} navigate={navigate} />,
    dishes:       <DishesView       key={"di"+tick} query={query} />,
    customers: <CustomersView key={"cu"+tick}  query={query} />,
    orders:    <OrdersView    key={"or"+tick}  query={query} />,
    ops:       <OpsView       key={"op"+tick}  />,
    controls:  <ControlsView  key={"co"+tick}  />,
    notify:    <NotificationsView key={"no"+tick} />,
    settings:  <SettingsView  key={"se"+tick}  navigate={navigate} />,
    crm:       <CRMView       key={"cr"+tick}  />,
  };

  // ── Permission gate for the current view ──
  const ta = window.BC_teamAccess;
  const allowed = !ta || canSeeScreen(ta.can, view);
  const eff = ta ? ta.getEffective() : { role:"founder", previewing:false };

  const content = allowed
    ? Views[view]
    : (
      <div className="bc-noaccess">
        <Icon name="key" size={40}/>
        <h2>No access to this section</h2>
        <p>Your role (<b>{eff.role}</b>) doesn't have permission to view this.
          Contact the founder if you need it.</p>
        <button className="bc-btn bc-btn--primary" onClick={()=>navigate("overview")}>Back to Home</button>
      </div>
    );

  return (
    <div className="bc-app">
      <Sidebar view={view} setView={setView} minimized={sidebarMinimized} onToggleSidebar={() => setSidebarMinimized(!sidebarMinimized)}/>
      <main className="bc-main">
        <Topbar view={view} query={query} setQuery={setQuery} navigate={navigate}/>
        <div className="bc-content">{content}</div>
      </main>
      <MobileNav view={view} setView={setView}/>
      <TeamPreviewBar navigate={navigate}/>

      <TweaksPanel>
        <TweakSection label="Brand"/>
        <TweakColor  label="Accent"       value={t.accent}      options={Object.keys(ACCENTS)} onChange={v=>setTweak("accent",v)}/>
        <TweakSelect label="Heading font" value={t.headingFont}  options={HEAD_FONTS}           onChange={v=>setTweak("headingFont",v)}/>
        <TweakSection label="Surface"/>
        <TweakRadio  label="Theme"        value={theme}          options={["light","dark"]}             onChange={v=>{setTweak("theme",v); window.BC_theme.set(v);}}/>
        <TweakRadio  label="Density"      value={t.density}      options={["compact","regular","comfy"]} onChange={v=>setTweak("density",v)}/>
        <TweakSlider label="Corner radius" value={t.radius} min={4} max={22} unit="px"                  onChange={v=>setTweak("radius",v)}/>
      </TweaksPanel>
    </div>
  );
}

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