/*  App composition + small floating Tweaks panel. v2 */

const useSettings = () => {
  const [s, setS] = React.useState(() => window.APP_SETTINGS || {});
  React.useEffect(() => {
    if (!window.onSettingsChange) return;
    return window.onSettingsChange(next => setS({ ...next }));
  }, []);
  return s;
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "petals": true,
  "messageLayout": "postit"
}/*EDITMODE-END*/;

const useTweaks = (defaults) => {
  const [t, setT] = React.useState(defaults);
  const set = (k, v) => {
    const update = typeof k === "object" ? k : { [k]: v };
    setT(prev => ({ ...prev, ...update }));
    try {
      window.parent.postMessage({ type: "__edit_mode_set_keys", edits: update }, "*");
    } catch(e) {}
  };
  return [t, set];
};

const TweaksPanel = ({ tweaks, setTweak, onClose, showGallery, showPhotoUpload, autoActive }) => (
  <div style={{
    width: 280,
    background:"#FFFCF7",
    borderRadius: 22,
    boxShadow:"0 24px 60px rgba(74,60,50,.22)",
    border:"1px solid #E6E9DD",
    overflow:"hidden",
  }}>
    <div style={{
      display:"flex", justifyContent:"space-between", alignItems:"center",
      padding: "16px 18px",
      borderBottom:"1px solid #E6E9DD",
      background:"#F0E8DC",
    }}>
      <span style={{ font:'500 13px/1 "Manrope", sans-serif', letterSpacing:".2em", textTransform:"uppercase", color:"var(--sage)" }}>
        Tweaks
      </span>
      <button onClick={onClose} aria-label="kapat" style={{
        all:"unset", cursor:"pointer", padding: 6, borderRadius: 999,
        color:"var(--sage)",
      }}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 6l12 12M18 6L6 18"/></svg>
      </button>
    </div>
    <div style={{ padding: 18, display:"grid", gap: 18 }}>
      <div>
        <div style={{ font:'500 11px/1 "Manrope", sans-serif', letterSpacing:".18em", textTransform:"uppercase", color:"var(--muted)", marginBottom: 8 }}>
          Hero
        </div>
        <label style={{ display:"flex", alignItems:"center", justifyContent:"space-between", gap: 10 }}>
          <span style={{ fontSize: 14, color:"var(--ink)" }}>Yaprak yağmuru</span>
          <input type="checkbox" checked={tweaks.petals} onChange={e=> setTweak("petals", e.target.checked)} />
        </label>
      </div>
      <div>
        <div style={{ font:'500 11px/1 "Manrope", sans-serif', letterSpacing:".18em", textTransform:"uppercase", color:"var(--muted)", marginBottom: 8 }}>
          Mesaj duvarı stili
        </div>
        <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap: 8 }}>
          {[["postit","Post-it"],["card","Kart"]].map(([v,l])=>(
            <button key={v} onClick={()=> setTweak("messageLayout", v)} style={{
              all:"unset", cursor:"pointer",
              padding: "10px 12px", borderRadius: 10,
              border:"1.5px solid",
              borderColor: tweaks.messageLayout===v ? "var(--coral)" : "#E6E9DD",
              background: tweaks.messageLayout===v ? "#FBE6E2" : "transparent",
              color: tweaks.messageLayout===v ? "var(--coral)" : "var(--ink)",
              fontSize: 14, textAlign:"center", fontWeight: 500,
            }}>{l}</button>
          ))}
        </div>
      </div>
      <div style={{ borderTop:"1px dashed #E6E9DD", paddingTop: 14 }}>
        <div style={{ font:'500 11px/1 "Manrope", sans-serif', letterSpacing:".18em", textTransform:"uppercase", color:"var(--coral)", marginBottom: 10 }}>
          🔑 Görünürlük
        </div>
        {autoActive && (
          <p style={{ margin:"0 0 10px", font:'500 12px/1.4 "Manrope", sans-serif', color:"var(--sage)", background:"#E6E9DD", padding:"8px 12px", borderRadius: 10 }}>
            🎉 Düğün günü — otomatik aktif
          </p>
        )}
        <label style={{ display:"flex", alignItems:"center", justifyContent:"space-between", gap: 10, marginBottom: 10, opacity: .75 }}>
          <span style={{ fontSize: 14, color:"var(--ink)" }}>Fotoğraf yükleme bölümü</span>
          <input type="checkbox" checked={showPhotoUpload} disabled />
        </label>
        <label style={{ display:"flex", alignItems:"center", justifyContent:"space-between", gap: 10, opacity: .75 }}>
          <span style={{ fontSize: 14, color:"var(--ink)" }}>Galeri önizleme</span>
          <input type="checkbox" checked={showGallery} disabled />
        </label>
        <p style={{ margin:"10px 0 0", font:'italic 400 12px/1.4 "Cormorant Garamond", serif', color:"var(--muted)" }}>
          Supabase settings tablosundan yönetilir. Admin paneli hazır olunca buradan açılır.
        </p>
      </div>
    </div>
  </div>
);

/* small nav for desktop */
const TopNav = () => {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(()=>{
    const onScroll = () => setScrolled(window.scrollY > 80);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <nav style={{
      position:"fixed", top: 0, left: 0, right: 0, zIndex: 50,
      background: scrolled ? "rgba(250,245,239,.92)" : "transparent",
      backdropFilter: scrolled ? "saturate(1.2) blur(8px)" : "none",
      WebkitBackdropFilter: scrolled ? "saturate(1.2) blur(8px)" : "none",
      borderBottom: scrolled ? "1px solid rgba(90,107,71,.12)" : "1px solid transparent",
      transition:"all .35s ease",
    }}>
      <div className="container" style={{ display:"flex", alignItems:"center", justifyContent:"space-between", padding:"14px 22px" }}>
        <a href="#top" style={{ font:'400 28px/1 "Allura", cursive', color:"var(--coral)", textDecoration:"none" }}>
          B & S
        </a>
        <div className="nav-links" style={{ display:"flex", gap: 22 }}>
          {[["#davet","Davet"],["#rsvp","Katılım"],["#mesaj","Mesajlar"],["#sss","SSS"]].map(([h,t])=>(
            <a key={t} href={h} style={{
              font:'500 13px/1 "Manrope", sans-serif',
              letterSpacing:".15em", textTransform:"uppercase",
              color:"var(--sage)", textDecoration:"none",
            }}>{t}</a>
          ))}
        </div>
        <a className="btn btn-primary" href="#rsvp" style={{ padding:"10px 18px", fontSize: 14 }}>
          Katılım Durumu
        </a>
      </div>
      <style>{`
        @media (max-width: 740px){ .nav-links{ display: none !important; } }
      `}</style>
    </nav>
  );
};

const App = () => {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [editing, setEditing] = React.useState(false);

  const settings = useSettings();
  const vis = settings.visibility || {};
  const autoAt = vis.auto_activate_at ? new Date(vis.auto_activate_at).getTime() : Infinity;
  const autoActive = Date.now() >= autoAt;
  const showGallery     = !!(vis.show_gallery     || autoActive);
  const showPhotoUpload = !!(vis.show_photo_upload || autoActive);

  useReveal();

  React.useEffect(() => {
    const onMsg = (e) => {
      const d = e.data;
      if (!d || typeof d !== "object") return;
      if (d.type === "__activate_edit_mode")   setEditing(true);
      if (d.type === "__deactivate_edit_mode") setEditing(false);
    };
    window.addEventListener("message", onMsg);
    try { window.parent.postMessage({ type: "__edit_mode_available" }, "*"); } catch(e){}
    return () => window.removeEventListener("message", onMsg);
  }, []);

  const closePanel = () => {
    setEditing(false);
    try { window.parent.postMessage({ type: "__edit_mode_dismissed" }, "*"); } catch(e){}
  };

  return (
    <div id="top">
      <TopNav />
      <Hero tweaks={tweaks} />
      <Welcome />
      <div id="rsvp-anchor"><RSVP /></div>
      <Details />
      <Location />
      <Story />
      <div id="mesaj"><MessageWall layout={tweaks.messageLayout}/></div>
      {showGallery     && <GalleryPreview />}
      {showPhotoUpload && <PhotoCTA />}
      <div id="sss"><FAQ /></div>
      <Hotels />
      <Gift />
      <Footer />

      {editing && (
        <div id="tweaks-host">
          <TweaksPanel tweaks={tweaks} setTweak={setTweak} onClose={closePanel}
            showGallery={showGallery} showPhotoUpload={showPhotoUpload} autoActive={autoActive} />
        </div>
      )}
    </div>
  );
};

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