// App shell — routing, tweaks panel, edit-mode wiring.

const { useState: useStateA, useEffect: useEffectA } = React;

function parseHash() {
  const h = window.location.hash || "#/";
  if (h === "#/" || h === "" || h === "#") return { route: "directory" };
  const slug = h.slice(2).split("/")[0];
  if (slug) return { route: "profile", slug };
  return { route: "directory" };
}

function App({ initialTweaks }) {
  const [route, setRoute] = useStateA(parseHash());
  const [tweaks, setTweaksRaw] = useStateA(initialTweaks);
  const [editMode, setEditMode] = useStateA(false);

  // Hash routing
  useEffectA(() => {
    const onHash = () => setRoute(parseHash());
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  // Persist last-viewed route
  useEffectA(() => {
    try { localStorage.setItem("assurix.dir.route", window.location.hash); } catch {}
  }, [route]);
  useEffectA(() => {
    try {
      const saved = localStorage.getItem("assurix.dir.route");
      if (saved && !window.location.hash) window.location.hash = saved;
    } catch {}
  }, []);

  // Tweaks: wired up to both local state + edit-mode host
  const setTweaks = (patch) => {
    const next = typeof patch === "function" ? patch(tweaks) : { ...tweaks, ...patch };
    setTweaksRaw(next);
    try { localStorage.setItem("assurix.dir.tweaks", JSON.stringify(next)); } catch {}
    // Send only the keys that changed to the host
    const diff = {};
    Object.keys(next).forEach(k => { if (next[k] !== tweaks[k]) diff[k] = next[k]; });
    if (Object.keys(diff).length) {
      try { window.parent.postMessage({ type: "__edit_mode_set_keys", edits: diff }, "*"); } catch {}
    }
  };

  // Edit-mode protocol
  useEffectA(() => {
    const onMsg = (e) => {
      const t = e.data && e.data.type;
      if (t === "__activate_edit_mode") setEditMode(true);
      if (t === "__deactivate_edit_mode") setEditMode(false);
    };
    window.addEventListener("message", onMsg);
    try { window.parent.postMessage({ type: "__edit_mode_available" }, "*"); } catch {}
    return () => window.removeEventListener("message", onMsg);
  }, []);

  // Restore tweaks from local storage too
  useEffectA(() => {
    try {
      const saved = JSON.parse(localStorage.getItem("assurix.dir.tweaks") || "null");
      if (saved) setTweaksRaw(t => ({ ...t, ...saved }));
    } catch {}
  }, []);

  const tweaksWithSetter = { ...tweaks, set: (k,v) => setTweaks({ [k]: v }) };

  const goHome = () => { window.location.hash = "#/"; };
  const openMsp = (slug) => { window.location.hash = `#/${slug}`; };

  return (
    <div data-screen-label={route.route === "profile" ? `Profile: ${route.slug}` : "Directory"} style={{
      background: "#F4F7FB",
      minHeight:"100vh",
      fontFamily:window.ASX.font,
      color:"#071e47",
      "--accent": tweaks.accent,
    }}>
      <TopNav onGoHome={goHome}/>

      {route.route === "directory" && <DirectoryView tweaks={tweaksWithSetter} onOpenMsp={openMsp}/>}
      {route.route === "profile"   && <ProfileView slug={route.slug} onBack={goHome}/>}

      <Footer/>

      {editMode && <TweaksPanel tweaks={tweaks} setTweaks={setTweaks}/>}
    </div>
  );
}

// ---------- Tweaks panel ---------------------------------------------------
function TweaksPanel({ tweaks, setTweaks }) {
  return (
    <div style={{
      position:"fixed", right:20, bottom:20, zIndex:100,
      width:300,
      background:"#fff", borderRadius:14,
      boxShadow:"0 20px 60px -10px rgba(11,21,51,0.35), 0 2px 6px rgba(11,21,51,0.08)",
      border:"1px solid #E4E9F2",
      fontSize:13,
      color:"#071e47",
      overflow:"hidden",
    }}>
      <div style={{padding:"14px 16px", background:"#071e47", color:"#fff", display:"flex", alignItems:"center", gap:10}}>
        <Icon name="sliders" size={14}/>
        <div style={{flex:1, fontSize:13, fontWeight:600}}>Tweaks</div>
        <span style={{fontSize:10, color:"rgba(255,255,255,0.5)"}}>preview</span>
      </div>
      <div style={{padding:"14px 16px", display:"flex", flexDirection:"column", gap:16}}>
        <TweakRow label="Default layout">
          <SegButtons value={tweaks.layout} onChange={v=>setTweaks({layout:v})} options={[
            {v:"grid", l:"Grid"},
            {v:"list", l:"List"},
            {v:"map",  l:"Map"},
          ]}/>
        </TweakRow>

        <TweakRow label="Card density">
          <SegButtons value={tweaks.density} onChange={v=>setTweaks({density:v})} options={[
            {v:"comfy",   l:"Comfortable"},
            {v:"compact", l:"Compact"},
          ]}/>
        </TweakRow>

        <TweakRow label="Grid columns">
          <SegButtons value={String(tweaks.perRow)} onChange={v=>setTweaks({perRow:parseInt(v)})} options={[
            {v:"2", l:"2"},
            {v:"3", l:"3"},
          ]}/>
        </TweakRow>

        <TweakRow label="Mini trustmark on cards">
          <Toggle value={tweaks.showMark} onChange={v=>setTweaks({showMark:v})}/>
        </TweakRow>

        <TweakRow label="Accent">
          <div style={{display:"flex", gap:6}}>
            {["#2a9d8f","#b8d645","#3B82F6","#F59E0B"].map(c => (
              <button key={c} onClick={()=>setTweaks({accent:c})} style={{
                width:24, height:24, borderRadius:6,
                border: tweaks.accent===c ? "2px solid #071e47" : "1px solid #E4E9F2",
                background:c, cursor:"pointer",
              }}/>
            ))}
          </div>
        </TweakRow>

        <div style={{borderTop:"1px dashed #E4E9F2", paddingTop:10, fontSize:11, color:"#6B7793", lineHeight:1.5}}>
          Tip: click an MSP to open its profile.
        </div>
      </div>
    </div>
  );
}

function TweakRow({ label, children }) {
  return (
    <div>
      <div style={{fontSize:11, color:"#6B7793", textTransform:"uppercase", letterSpacing:"0.05em", fontWeight:600, marginBottom:8}}>{label}</div>
      {children}
    </div>
  );
}

function SegButtons({ value, onChange, options }) {
  return (
    <div style={{display:"flex", background:"#F4F7FB", borderRadius:8, padding:3, border:"1px solid #E4E9F2"}}>
      {options.map(o => (
        <button key={o.v} onClick={()=>onChange(o.v)} style={{
          flex:1, border:"none", background: value===o.v ? "#071e47" : "transparent",
          color: value===o.v ? "#fff" : "#39466A",
          padding:"6px 8px", borderRadius:6,
          fontSize:12, fontWeight:500,
          cursor:"pointer", fontFamily:"inherit",
        }}>{o.l}</button>
      ))}
    </div>
  );
}

function Toggle({ value, onChange }) {
  return (
    <button onClick={()=>onChange(!value)} style={{
      width:40, height:22, borderRadius:99,
      background: value ? "#2a9d8f" : "#E4E9F2",
      border:"none", position:"relative",
      cursor:"pointer", transition:"background .15s",
    }}>
      <span style={{
        position:"absolute", top:2, left: value ? 20 : 2,
        width:18, height:18, borderRadius:99, background:"#fff",
        boxShadow:"0 1px 3px rgba(0,0,0,0.2)", transition:"left .15s",
      }}/>
    </button>
  );
}

window.App = App;
