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 BADGE_COLORS = {
  teacher:  { bg: "#E6E9DD", fg: "#5A6B47" },
  police:   { bg: "#DDE6EF", fg: "#3B5577" },
  military: { bg: "#EAE3D0", fg: "#6B5A2E" },
};

const parseBadge = (str, category) => {
  if (!str) return null;
  const match = str.match(/^(\S+)\s+(.+)$/);
  const c = BADGE_COLORS[category] || BADGE_COLORS.teacher;
  return match ? { emoji: match[1], label: match[2], ...c } : null;
};

/*  Page sections — Hero, Welcome, Story, Details, Program, Location,
    Messages, Photo CTA, Gallery, FAQ, Hotels, Gift, Footer.
    RSVP form lives in rsvp.jsx for size.                                  */

/* ------------------- shared bits ------------------- */

const useReveal = () => {
  React.useEffect(() => {
    const els = document.querySelectorAll(".reveal:not(.in)");
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting){ e.target.classList.add("in"); io.unobserve(e.target); }
      });
    }, { threshold: .12, rootMargin: "0px 0px -40px 0px" });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  });
};

const toast = (msg) => {
  const root = document.getElementById("toast-root");
  const el = document.createElement("div");
  el.style.cssText = `
    pointer-events:auto;
    background: #FFFCF7;
    border: 1px solid #E6E9DD;
    border-left: 4px solid #5A6B47;
    border-radius: 14px;
    padding: 14px 18px;
    font: 500 14px/1.4 "Manrope", sans-serif;
    color:#3E3B36;
    box-shadow: 0 12px 30px rgba(74,60,50,.16);
    transform: translateX(20px); opacity: 0;
    transition: transform .3s ease, opacity .3s ease;
    max-width: 320px;
  `;
  el.textContent = msg;
  root.appendChild(el);
  requestAnimationFrame(() => { el.style.opacity = 1; el.style.transform = "none"; });
  setTimeout(()=>{
    el.style.opacity = 0; el.style.transform = "translateX(20px)";
    setTimeout(()=> el.remove(), 350);
  }, 3200);
};

const launchConfetti = () => {
  const root = document.getElementById("confetti-root");
  const colors = ["#C9484D","#F4A5A0","#5A6B47","#FAD9C8","#E78A8C"];
  for (let i=0; i<80; i++){
    const c = document.createElement("span");
    const x = Math.random()*100;
    const dur = 2.5 + Math.random()*2.5;
    const size = 6 + Math.random()*9;
    c.style.cssText = `
      position:absolute; top:-20px; left:${x}vw;
      width:${size}px; height:${size*1.6}px;
      background:${colors[i%colors.length]};
      border-radius: ${Math.random()>.5?"50%":"2px"};
      opacity: .9;
      transform: rotate(${Math.random()*360}deg);
      animation: drift ${dur}s linear forwards;
      --dx:${(Math.random()-.5)*400}px;
      --rot:${Math.random()*720}deg;
    `;
    root.appendChild(c);
    setTimeout(()=> c.remove(), dur*1000);
  }
};

/* ------------------- HERO ------------------- */

const useCountdown = (target) => {
  const [now, setNow] = React.useState(()=> Date.now());
  React.useEffect(() => {
    const t = setInterval(()=> setNow(Date.now()), 1000);
    return ()=> clearInterval(t);
  }, []);
  const ms = Math.max(0, target - now);
  const s = Math.floor(ms/1000);
  return {
    days: Math.floor(s/86400),
    hours: Math.floor((s%86400)/3600),
    mins: Math.floor((s%3600)/60),
    secs: s%60,
  };
};

const FlipNumber = ({ value, label }) => {
  const [prev, setPrev] = React.useState(value);
  const [flip, setFlip] = React.useState(false);
  React.useEffect(()=>{
    if (value !== prev){
      setFlip(true);
      const t = setTimeout(()=> { setPrev(value); setFlip(false); }, 280);
      return ()=> clearTimeout(t);
    }
  }, [value, prev]);
  return (
    <div style={{
      background:"#FFFCF7",
      border:"1.5px solid rgba(201,72,77,.35)",
      borderRadius: 18,
      padding: "14px 6px 10px",
      minWidth: 72,
      textAlign:"center",
      boxShadow:"0 8px 22px rgba(74,60,50,.07)",
    }}>
      <div style={{
        font: '600 38px/1 "Cormorant Garamond", serif',
        color:"var(--coral)",
        fontVariantNumeric: "tabular-nums",
        animation: flip ? "flip-in .28s ease" : "none",
        transformOrigin: "center"
      }}>
        {String(value).padStart(2,"0")}
      </div>
      <div style={{
        font:'500 11px/1 "Manrope", sans-serif',
        color:"var(--sage)",
        letterSpacing:".18em",
        textTransform:"uppercase",
        marginTop: 8,
      }}>{label}</div>
    </div>
  );
};

const Hero = ({ tweaks }) => {
  const target = new Date("2026-07-04T19:00:00+03:00").getTime();
  const { days, hours, mins, secs } = useCountdown(target);
  return (
    <section style={{
      minHeight: "100vh",
      paddingTop: 72,
      paddingBottom: 72,
      display:"flex", alignItems:"center", justifyContent:"center",
      position:"relative",
      background: "radial-gradient(1200px 600px at 80% -10%, #FBE6E2 0%, transparent 60%), radial-gradient(900px 500px at -10% 110%, #E6E9DD 0%, transparent 65%), var(--cream)",
      overflow:"hidden",
    }}>
      {/* corner florals */}
      <div className="deco" style={{ top:-40, left:-60, opacity:.85 }}>
        <FloralCluster size={340} hue="peach" rotate={-20} />
      </div>
      <div className="deco" style={{ bottom:-50, right:-70, opacity:.95 }}>
        <FloralCluster size={360} hue="coral" rotate={150} />
      </div>
      <div className="deco" style={{ top:"30%", right:-40, opacity:.4, transform:"translateY(-50%)" }}>
        <BrushStroke width={300} color="#FAD9C8" opacity={.65} />
      </div>
      <div className="deco" style={{ bottom:"22%", left:-30, opacity:.4 }}>
        <BrushStroke width={260} color="#FAD9C8" opacity={.65} />
      </div>

      {/* petal rain */}
      {tweaks.petals && <PetalRain count={22} />}

      <div className="container center" style={{ position:"relative", zIndex:2 }}>
        <div className="eyebrow" style={{ animation: "fadeIn 1.2s ease both" }}>
          düğünümüze hoşgeldiniz
        </div>

        <h1 style={{
          margin: "22px 0 10px",
          font:'400 clamp(72px, 16vw, 168px)/.95 "Allura", cursive',
          color:"var(--coral)",
          letterSpacing:"-.01em",
          animation:"fadeUp 1.3s cubic-bezier(.2,.7,.2,1) both",
        }}>
          Berat <span style={{ color:"var(--coral-soft)", fontSize:".7em", verticalAlign:"middle"}}>&</span> Sude
        </h1>

        <div style={{ height: 14 }}></div>

        <div className="hero-datebar" style={{
          animation:"fadeUp 1.5s cubic-bezier(.2,.7,.2,1) .15s both",
        }}>
          <div className="hero-datecol">CUMARTESİ</div>
          <div className="hero-datemid">
            <div className="hero-month">TEMMUZ</div>
            <div className="hero-bigday">04</div>
            <div className="hero-year">2026</div>
          </div>
          <div className="hero-datecol">SAAT 19:00</div>
        </div>

        <style>{`
          .hero-datebar{
            display:flex;
            align-items:center;
            justify-content:center;
            gap: 28px;
            max-width: 640px;
            margin: 14px auto 0;
          }
          .hero-datecol{
            font: 500 clamp(16px, 1.9vw, 20px)/1.1 "Cormorant Garamond", serif;
            letter-spacing: .26em;
            text-transform: uppercase;
            color: var(--sage);
            white-space: nowrap;
            flex: 0 0 auto;
          }
          .hero-datemid{ text-align:center; padding: 0 4px; flex: 0 0 auto; }
          .hero-month{
            font: 500 clamp(16px, 1.9vw, 20px)/1 "Cormorant Garamond", serif;
            letter-spacing: .3em;
            text-transform: uppercase;
            color: var(--sage);
            margin-bottom: 6px;
          }
          .hero-bigday{
            font: 500 clamp(56px, 8vw, 82px)/.92 "Cormorant Garamond", serif;
            color: var(--coral);
            letter-spacing: .02em;
            transform: translateY(-7px);
          }
          .hero-year{
            font: 500 clamp(16px, 1.9vw, 20px)/1 "Cormorant Garamond", serif;
            font-variant-numeric: lining-nums;
            font-feature-settings: "lnum" 1, "onum" 0;
            letter-spacing: .3em;
            text-transform: uppercase;
            color: var(--sage);
            margin-top: 6px;
          }
          @media (max-width: 640px){
            .hero-datebar{
              gap: 16px;
              max-width: 100%;
            }
            .hero-datecol{
              font-size: 14px;
              letter-spacing: .14em;
            }
            .hero-datemid{ padding: 0 2px; }
          }
        `}</style>

        <div style={{
          display:"grid",
          gridTemplateColumns:"repeat(4, minmax(0, 1fr))",
          gap:10, maxWidth: 420, margin: "36px auto 28px",
          animation: "fadeUp 1.7s cubic-bezier(.2,.7,.2,1) .3s both",
        }}>
          <FlipNumber value={days}  label="Gün"/>
          <FlipNumber value={hours} label="Saat"/>
          <FlipNumber value={mins}  label="Dakika"/>
          <FlipNumber value={secs}  label="Saniye"/>
        </div>
      </div>

      <div style={{ position:"absolute", left:"50%", bottom: 26, transform:"translateX(-50%)", zIndex: 3 }}>
        <a href="#davet" aria-label="aşağı kaydır" style={{
          display:"flex", flexDirection:"column", alignItems:"center", gap:8,
          color:"var(--sage)", textDecoration:"none",
          animation:"floatUpDown 2.6s ease-in-out infinite",
          textAlign:"center",
        }}>
          <span style={{ fontFamily:"var(--serif)", fontStyle:"italic", fontSize: 15, fontWeight: 400 }}>aşağı kaydır</span>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M6 9l6 6 6-6"/></svg>
        </a>
      </div>
    </section>
  );
};

/* ------------------- CHILDHOOD PHOTOS ------------------- */

const ChildhoodPhotos = () => (
  <section style={{ background:"var(--cream)", position:"relative", overflow:"hidden" }}>
    {/* watercolor brush strokes behind, like davetiye */}
    <div className="deco" style={{ top:"32%", left:"4%", opacity:.55, transform:"rotate(-12deg)" }}>
      <BrushStroke width={420} color="#FAD9C8" opacity={.65} />
    </div>
    <div className="deco" style={{ top:"38%", right:"4%", opacity:.55, transform:"rotate(12deg)" }}>
      <BrushStroke width={420} color="#FAD9C8" opacity={.65} />
    </div>

    <div className="container">
      <header className="center reveal" style={{ maxWidth: 700, margin:"0 auto 24px" }}>
        <div className="eyebrow">Küçük Berat & Küçük Sude</div>
        <h2 style={{ margin:"14px 0 6px", font:'400 clamp(48px, 8vw, 78px)/.95 "Allura", cursive', color:"var(--coral)" }}>
          minik halimizden bugüne
        </h2>
        <p className="serif-i" style={{ color:"var(--muted)", marginTop: 6, fontSize: 18, textWrap:"pretty", maxWidth: 540, margin:"10px auto 0" }}>
          küçükken birbirimizin elini tuttuğumuz o gün
        </p>
      </header>

      <div className="childhood-wrap reveal">
        {/* names with hand-drawn arrows pointing down — like the davetiye */}
        <div className="childhood-name childhood-name-berat" aria-hidden="true">
          <span className="childhood-script">Berat</span>
          <svg width="56" height="80" viewBox="0 0 56 80" className="childhood-arrow-svg">
            <path d="M 8 6 C 18 28, 30 38, 44 60" fill="none" stroke="#C9484D" strokeWidth="2.4" strokeLinecap="round"/>
            <path d="M 44 60 L 38 52 M 44 60 L 50 52" fill="none" stroke="#C9484D" strokeWidth="2.4" strokeLinecap="round"/>
          </svg>
        </div>
        <div className="childhood-name childhood-name-sude" aria-hidden="true">
          <span className="childhood-script">Sude</span>
          <svg width="56" height="80" viewBox="0 0 56 80" className="childhood-arrow-svg">
            <path d="M 48 6 C 38 28, 26 38, 12 60" fill="none" stroke="#C9484D" strokeWidth="2.4" strokeLinecap="round"/>
            <path d="M 12 60 L 18 52 M 12 60 L 6 52" fill="none" stroke="#C9484D" strokeWidth="2.4" strokeLinecap="round"/>
          </svg>
        </div>

        <img
          src={(window.__resources && window.__resources.childhoodImg) || "assets/childhood-berat-sude.png"}
          alt="Çocukken Berat ve Sude el ele"
          className="childhood-img"
        />

        {/* watercolor floral cluster at the bottom of feet, like davetiye */}
        <div className="childhood-flower" aria-hidden="true">
          <FloralCluster size={260} hue="peach" rotate={0} opacity={1}/>
        </div>
      </div>
    </div>
    <style>{`
      .childhood-wrap{
        position: relative;
        max-width: 720px;
        margin: 0 auto;
        padding: 60px 0 40px;
      }
      .childhood-img{
        position: relative;
        z-index: 1;
        width: 100%;
        max-width: 640px;
        margin: 0 auto;
        display: block;
        filter: drop-shadow(0 18px 30px rgba(74,60,50,.18));
      }
      .childhood-name{
        position: absolute;
        z-index: 2;
        display: flex;
        flex-direction: column;
        align-items: center;
        top: 4%;
      }
      .childhood-name-berat{ left: 6%; }
      .childhood-name-sude{  right: 6%; }
      .childhood-script{
        font: 400 clamp(48px, 7vw, 78px)/1 "Allura", cursive;
        color: var(--coral);
        line-height: .9;
      }
      .childhood-arrow-svg{
        margin-top: -4px;
        filter: drop-shadow(0 1px 0 #FAF5EF);
      }
      .childhood-flower{
        position:absolute;
        left: 50%;
        bottom: -10px;
        transform: translateX(-50%);
        z-index: 2;
        pointer-events: none;
      }
      @media (max-width: 640px){
        .childhood-wrap{ padding: 40px 0 20px; }
        .childhood-name-berat{ left: 0; }
        .childhood-name-sude{  right: 0; }
        .childhood-flower svg{ width: 180px !important; height: 180px !important; }
      }
    `}</style>
  </section>
);

/* ------------------- WELCOME / DAVET ------------------- */

const Welcome = () => (
  <section id="davet" style={{ background:"var(--cream)" }}>
    <div className="container reveal" style={{ maxWidth: 720, textAlign:"center" }}>
      <HorizontalRule color="#5A6B47" />
      <div style={{ marginTop: 28, display:"flex", alignItems:"flex-start", justifyContent:"center", gap:"clamp(20px, 6vw, 56px)", flexWrap:"wrap" }}>
        <div>
          <div className="eyebrow" style={{ fontSize: "clamp(11px, 2.4vw, 13px)" }}>Ermiş Ailesi</div>
          <div style={{ font:'500 clamp(17px, 2.4vw, 22px)/1.3 "Cormorant Garamond", serif', color:"var(--coral)", marginTop: 8, whiteSpace:"nowrap" }}>
            Burak &amp; Gülsüm Ermiş
          </div>
        </div>
        <div>
          <div className="eyebrow" style={{ fontSize: "clamp(11px, 2.4vw, 13px)" }}>Ertürk Ailesi</div>
          <div style={{ font:'500 clamp(17px, 2.4vw, 22px)/1.3 "Cormorant Garamond", serif', color:"var(--coral)", marginTop: 8, whiteSpace:"nowrap" }}>
            Hasan &amp; Songül Ertürk
          </div>
        </div>
      </div>
      <p style={{
        font:'italic 500 clamp(22px, 3.2vw, 30px)/1.6 "Cormorant Garamond", serif',
        color:"var(--sage)",
        margin:"28px auto",
        textWrap:"pretty",
      }}>
        Hayatımızın en güzel anına şahit olmanızı istiyoruz. Birlikte gülmek,
        birlikte dans etmek ve bu yolculuğun başlangıcını sizinle paylaşmak
        bizim için en büyük hediye olacak.
      </p>
      <div style={{
        font:'500 14px/1 "Manrope", sans-serif',
        color:"var(--coral)",
        letterSpacing:".3em",
        textTransform:"uppercase",
      }}>
        Sizleri aramızda görmek dileğiyle
      </div>

      <div className="deco" style={{ top:"50%", left:-40, transform:"translateY(-50%)", opacity:.55 }}>
        <FloralCluster size={140} hue="peach" rotate={-30} />
      </div>
      <div className="deco" style={{ top:"50%", right:-40, transform:"translateY(-50%)", opacity:.55 }}>
        <FloralCluster size={140} hue="coral" rotate={30} />
      </div>
    </div>
  </section>
);

/* ------------------- STORY TIMELINE ------------------- */

const StoryCard = ({ item, side }) => (
  <article className="card reveal" style={{
    background:"#FFFCF7",
    borderRadius: 28,
    boxShadow:"var(--shadow-2)",
    padding: "26px 28px",
    position:"relative",
    overflow:"hidden",
  }}>
    {/* mini brush */}
    <div style={{ position:"absolute", top:-30, [side==="left" ? "right" : "left"]:-30, opacity:.6, pointerEvents:"none" }}>
      <BrushStroke width={180} color={item.title === "Düğün" ? "#FAD9C8" : "#E6E9DD"} />
    </div>
    <div style={{
      font:'600 44px/1 "Cormorant Garamond", serif',
      color:"var(--coral)",
      letterSpacing:".02em",
    }}>{item.year}</div>
    <h3 style={{
      margin:"8px 0 10px",
      font:'500 22px/1.2 "Cormorant Garamond", serif',
      color:"var(--sage)",
      letterSpacing:".02em",
    }}>{item.title}{item.title==="Düğün" && " 💕"}</h3>
    <p style={{ margin: 0, color:"var(--muted)", fontSize: 15.5, lineHeight: 1.6, textWrap:"pretty" }}>
      {item.body}
    </p>
  </article>
);

const Story = () => {
  const settings = useSettings();
  const timeline = settings.story_timeline || [];
  return (
    <section style={{ background:"var(--cream)" }}>
      <div className="container">
        <header className="center reveal" style={{ maxWidth: 700, margin:"0 auto 36px" }}>
          <div className="eyebrow">Bizim Hikayemiz</div>
          <h2 style={{
            margin:"14px 0 6px",
            font:'400 clamp(48px, 8vw, 86px)/.95 "Allura", cursive',
            color:"var(--coral)",
          }}>kısa bir özet</h2>
          <p className="serif-i" style={{ color:"var(--muted)", fontSize: 18, marginTop: 6 }}>
            bizi buraya getiren küçük büyük anlar
          </p>
        </header>

        <figure className="reveal" style={{
          margin: "0 auto 64px",
          maxWidth: 520,
          textAlign: "center",
        }}>
          <img
            src={(window.__resources && window.__resources.childhoodImg) || "assets/childhood-berat-sude.png"}
            alt="Çocukken Berat ve Sude el ele"
            style={{
              width: "100%",
              maxWidth: 440,
              margin: "0 auto",
              display: "block",
              filter: "drop-shadow(0 18px 28px rgba(74,60,50,.16))",
            }}
          />
          <figcaption className="serif-i" style={{
            marginTop: 18,
            color: "var(--sage)",
            fontSize: "clamp(17px, 2.2vw, 21px)",
            lineHeight: 1.55,
            textWrap: "pretty",
            maxWidth: 460,
            marginInline: "auto",
          }}>
            Belki o yıllarda birbirimizi tanımıyorduk —<br/>
            ama bu sevgi, ikimizin de içindeki çocuğu yeniden uyandırdı.
          </figcaption>
        </figure>

        {/* Desktop: zigzag with center line */}
        <div className="story-grid">
          {timeline.map((s, i) => {
            const side = i % 2 === 0 ? "left" : "right";
            return (
              <div key={s.year} className={`story-row story-${side}`}>
                <div className="story-cell story-cell-card">
                  <StoryCard item={{ ...s, body: s.description }} side={side} />
                </div>
                <div className="story-node" aria-hidden="true">
                  <span className="story-dot">
                    <TinyFlower size={22} color="#C9484D"/>
                  </span>
                </div>
                <div className="story-cell story-cell-spacer"></div>
              </div>
            );
          })}
          <div className="story-line" aria-hidden="true"></div>
        </div>
      </div>

      <style>{`
        .story-grid{ position:relative; max-width: 1000px; margin: 0 auto; }
        .story-line{
          position:absolute; left: 22px; top: 0; bottom: 0;
          width: 2px; background: linear-gradient(180deg, transparent, #C9484D40 8%, #C9484D40 92%, transparent);
          border-radius: 2px;
        }
        .story-row{
          display:grid;
          grid-template-columns: 44px 1fr;
          gap: 18px;
          margin-bottom: 40px;
          position:relative;
        }
        .story-row .story-cell-spacer{ display: none; }
        .story-row .story-cell-card{ grid-column: 2; }
        .story-node{
          grid-column: 1; grid-row: 1;
          display:flex; justify-content:center; align-items: flex-start;
          padding-top: 28px;
          position:relative; z-index: 1;
        }
        .story-dot{
          width:44px; height:44px; border-radius:50%;
          background:#FFFCF7; border:1.5px solid #E78A8C40;
          display:inline-flex; align-items:center; justify-content:center;
          box-shadow: 0 6px 14px rgba(201,72,77,.12);
        }
        @media (min-width: 900px){
          .story-grid{ }
          .story-line{ left: 50%; transform: translateX(-1px); }
          .story-row{
            grid-template-columns: 1fr 60px 1fr;
            gap: 24px;
            margin-bottom: 36px;
          }
          .story-row .story-cell-card{ grid-column: auto; }
          .story-row .story-cell-spacer{ display: block; }
          .story-row.story-left .story-cell-card{ grid-column: 1; }
          .story-row.story-left .story-cell-spacer{ grid-column: 3; }
          .story-row.story-right .story-cell-spacer{ grid-column: 1; }
          .story-row.story-right .story-cell-card{ grid-column: 3; }
          .story-node{ grid-column: 2; padding-top: 22px; }
        }
      `}</style>
    </section>
  );
};

/* ------------------- DETAILS + PROGRAM ------------------- */

const DetailRow = ({ icon, label, value }) => (
  <li style={{ display:"flex", gap: 16, alignItems:"flex-start", padding: "14px 0", borderBottom:"1px dashed #E6E9DD" }}>
    <span style={{
      width: 40, height: 40, flex:"0 0 40px",
      borderRadius: 12,
      background: "#FBE6E2",
      color: "var(--coral)",
      display:"inline-flex", alignItems:"center", justifyContent:"center",
    }}>{icon}</span>
    <div>
      <div style={{ font:'500 12px/1 "Manrope", sans-serif', letterSpacing:".18em", textTransform:"uppercase", color:"var(--sage)" }}>{label}</div>
      <div style={{ font:'500 17px/1.4 "Cormorant Garamond", serif', color:"var(--ink)", marginTop: 6 }}>{value}</div>
    </div>
  </li>
);

const Icon = {
  date: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M8 3v4M16 3v4M3 10h18"/></svg>,
  time: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>,
  pin:  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M12 22s7-7.5 7-13a7 7 0 1 0-14 0c0 5.5 7 13 7 13Z"/><circle cx="12" cy="9" r="2.5"/></svg>,
  shirt:<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M4 7l4-3 2 2h4l2-2 4 3-2 4h-2v9H8v-9H6z"/></svg>,
  fork: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M6 3v8a2 2 0 0 0 2 2v8M10 3v6M6 9h4M16 3c2 0 3 1.5 3 4s-1 4-3 4v10"/></svg>,
  music:<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M9 18V5l10-2v13"/><circle cx="7" cy="18" r="2"/><circle cx="17" cy="16" r="2"/></svg>,
  cake: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M4 21V12h16v9M2 21h20M8 12V8M12 12V6M16 12V8M12 6V3"/></svg>,
  ring: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="14" r="6"/><path d="M9 7l3-4 3 4"/></svg>,
  henna:<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M12 21s7-6 7-12a5 5 0 0 0-7-4 5 5 0 0 0-7 4c0 6 7 12 7 12Z"/></svg>,
  wave: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M3 12c2-3 4-3 6 0s4 3 6 0 4-3 6 0"/></svg>,
};

const PROGRAM_ICONS = [Icon.wave, Icon.music, Icon.fork, Icon.cake, Icon.henna, Icon.ring];

const Details = () => {
  const settings = useSettings();
  const schedule = settings.schedule || [];
  return (
  <section style={{ background:"var(--cream-dark)", position:"relative", overflow:"hidden" }}>
    <div className="deco" style={{ top:-30, left:-50, opacity:.5 }}>
      <FloralCluster size={220} hue="peach" rotate={-30}/>
    </div>
    <div className="deco" style={{ bottom:-30, right:-40, opacity:.55 }}>
      <FloralCluster size={220} hue="coral" rotate={180}/>
    </div>

    <div className="container">
      <header className="center reveal" style={{ maxWidth: 700, margin:"0 auto 56px" }}>
        <div className="eyebrow">Düğün Detayları</div>
        <h2 style={{ margin:"14px 0 6px", font:'400 clamp(48px, 8vw, 78px)/.95 "Allura", cursive', color:"var(--coral)" }}>günün akışı</h2>
      </header>

      <div className="details-grid">
        <div className="card reveal" style={{ background:"#FFFCF7" }}>
          <h3 style={{ margin:"0 0 8px", font:'500 22px/1 "Cormorant Garamond", serif', color:"var(--sage)", letterSpacing:".06em", textTransform:"uppercase" }}>
            Etkinlik bilgileri
          </h3>
          <ul style={{ listStyle:"none", padding:0, margin: "16px 0 22px" }}>
            <DetailRow icon={Icon.date}  label="Tarih"    value="4 Temmuz 2026, Cumartesi"/>
            <DetailRow icon={Icon.time}  label="Saat"     value="19:00"/>
            <DetailRow icon={Icon.pin}   label="Yer"      value="Kozlu Garden Düğün Salonu, Kozlu / Zonguldak"/>
            <DetailRow icon={Icon.shirt} label="Kıyafet"  value="Şık / Yarı resmi"/>
          </ul>
          <div style={{ display:"flex", gap:10, flexWrap:"wrap" }}>
            <a className="btn btn-secondary" href="#" onClick={(e)=>{ e.preventDefault(); toast("Takvim dosyası indirildi 📅"); }}>
              📅 Takvime ekle
            </a>
          </div>
        </div>

        <div className="card reveal" style={{ background:"#FFFCF7" }}>
          <h3 style={{ margin:"0 0 8px", font:'500 22px/1 "Cormorant Garamond", serif', color:"var(--sage)", letterSpacing:".06em", textTransform:"uppercase" }}>
            Akşamın Akışı
          </h3>
          <ol style={{ listStyle:"none", padding:0, margin: "16px 0 0" }}>
            {schedule.map((p,i)=>(
              <li key={p.time || i} style={{
                display:"grid",
                gridTemplateColumns: "60px 28px 1fr",
                alignItems:"center",
                gap: 14,
                padding: "14px 12px",
                borderRadius: 14,
                background: p.highlighted ? "#FBE6E2" : "transparent",
                marginBottom: 6,
                border: p.highlighted ? "1px solid #F4A5A040" : "1px solid transparent",
              }}>
                <span style={{ font:'600 17px/1 "Cormorant Garamond", serif', color: p.highlighted ? "var(--coral)" : "var(--sage)" }}>{p.time}</span>
                <span style={{ color: p.highlighted ? "var(--coral)" : "var(--sage)" }}>{PROGRAM_ICONS[i] || Icon.wave}</span>
                <span style={{ font:'500 15px/1.3 "Manrope", sans-serif', color: p.highlighted ? "var(--coral)" : "var(--ink)" }}>
                  {p.title}{p.highlighted && " 🌿"}
                </span>
              </li>
            ))}
          </ol>
        </div>
      </div>
    </div>
    <style>{`
      .details-grid{ display:grid; grid-template-columns: 1fr; gap: 22px; }
      @media (min-width: 900px){ .details-grid{ grid-template-columns: 1fr 1fr; gap: 32px; } }
    `}</style>
  </section>
  );
};

/* ------------------- LOCATION ------------------- */

const VENUE = {
  // Kozlu Garden Düğün Salonu — Milli Egemenlik Cd, Kozlu/Zonguldak
  lat: 41.436145,
  lng: 31.736815,
  zoom: 15,
};

const VenueMap = () => {
  const ref = React.useRef(null);
  const mapRef = React.useRef(null);
  const layersRef = React.useRef({});
  const [mode, setMode] = React.useState("map");  // "map" | "sat"

  React.useEffect(()=>{
    if (!ref.current || !window.L) return;
    const map = L.map(ref.current, {
      center: [VENUE.lat, VENUE.lng],
      zoom: VENUE.zoom,
      minZoom: VENUE.zoom,
      maxZoom: 19,
      scrollWheelZoom: false,
      zoomControl: true,
      attributionControl: true,
    });
    mapRef.current = map;

    // tema ile uyumlu harita katmanı (default)
    const themed = L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png', {
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="https://carto.com/attributions">CARTO</a>',
      subdomains: 'abcd',
      maxZoom: 19,
    });
    // uydu (Esri)
    const satellite = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
      attribution: 'Tiles &copy; Esri — Source: Esri, Maxar, Earthstar Geographics',
      maxZoom: 19,
    });
    const satLabels = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServer/tile/{z}/{y}/{x}', {
      maxZoom: 19, opacity: .9,
    });

    layersRef.current = { themed, satellite, satLabels };
    themed.addTo(map);

    // custom coral heart pin
    const pin = L.divIcon({
      className: "venue-pin",
      html: `
        <div class="venue-pin-wrap">
          <svg viewBox="0 0 40 44" width="40" height="44">
            <defs>
              <filter id="vpf" x="-30%" y="-10%" width="160%" height="160%">
                <feGaussianBlur stdDeviation="1.2" result="b"/>
                <feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
              </filter>
            </defs>
            <path filter="url(#vpf)" fill="#C9484D" stroke="#FAF5EF" stroke-width="2.4"
              d="M20 40 C 20 40 4 28 4 15 C 4 9 9 4 14.5 4 C 17.5 4 20 5.6 20 9 C 20 5.6 22.5 4 25.5 4 C 31 4 36 9 36 15 C 36 28 20 40 20 40 Z"/>
            <circle cx="20" cy="14" r="2.6" fill="#FAF5EF" opacity=".6"/>
          </svg>
        </div>
      `,
      iconSize: [40,44],
      iconAnchor: [20,42],
      popupAnchor: [0,-38],
    });

    L.marker([VENUE.lat, VENUE.lng], { icon: pin })
      .addTo(map)
      .bindPopup(`<div style="font-family:'Cormorant Garamond',serif;text-align:center;line-height:1.3"><strong style="color:#C9484D;font-size:17px">Kozlu Garden Düğün Salonu</strong><br><span style="color:#5A6B47;font-size:13px">04 Temmuz 2026 · 19:00</span></div>`);

    return () => { map.remove(); mapRef.current = null; };
  }, []);

  // toggle modes
  React.useEffect(()=>{
    const map = mapRef.current;
    const L = window.L;
    const { themed, satellite, satLabels } = layersRef.current;
    if (!map || !themed) return;
    if (mode === "sat"){
      if (map.hasLayer(themed))   map.removeLayer(themed);
      if (!map.hasLayer(satellite)) satellite.addTo(map);
      if (!map.hasLayer(satLabels)) satLabels.addTo(map);
    } else {
      if (map.hasLayer(satellite)) map.removeLayer(satellite);
      if (map.hasLayer(satLabels)) map.removeLayer(satLabels);
      if (!map.hasLayer(themed))   themed.addTo(map);
    }
  }, [mode]);

  return (
    <div className="reveal" style={{
      borderRadius: 28,
      overflow:"hidden",
      boxShadow:"var(--shadow-2)",
      background:"#fff",
      aspectRatio: "4 / 3",
      minHeight: 320,
      position:"relative",
    }}>
      <div ref={ref} style={{ width:"100%", height:"100%" }}/>

      {/* mode toggle (top-right) */}
      <div className="map-mode-toggle" role="group" aria-label="Harita görünümü">
        {[["map","Harita"],["sat","Uydu"]].map(([v,l])=>(
          <button key={v}
            onClick={()=> setMode(v)}
            aria-pressed={mode===v}
            style={{
              all:"unset", cursor:"pointer",
              padding:"7px 14px",
              font:'600 12px/1 "Manrope", sans-serif',
              letterSpacing:".1em",
              textTransform:"uppercase",
              color: mode===v ? "#fff" : "var(--coral)",
              background: mode===v ? "var(--coral)" : "transparent",
              borderRadius: 999,
              transition:"all .2s",
            }}
          >{l}</button>
        ))}
      </div>

      <style>{`
        .leaflet-container{
          background:#FBE6E2;
          font-family: "Manrope", sans-serif;
        }
        .map-mode-toggle{
          position:absolute; top: 14px; right: 14px;
          z-index: 600;
          display:inline-flex; gap: 2px;
          background: rgba(255,252,247,.95);
          padding: 4px;
          border-radius: 999px;
          box-shadow: 0 6px 16px rgba(74,60,50,.18);
          border: 1px solid #E6E9DD;
        }
        .leaflet-control-zoom a{
          background:#FFFCF7 !important;
          color: var(--coral) !important;
          border:1px solid #E6E9DD !important;
          font-weight: 600;
        }
        .leaflet-control-zoom a:hover{ background:#FBE6E2 !important; }
        .leaflet-control-attribution{
          background: rgba(250,245,239,.9) !important;
          font-size: 10px !important;
        }
        .venue-pin-wrap{ animation: floatUpDown 2.6s ease-in-out infinite; transform-origin: 50% 100%; }
      `}</style>
    </div>
  );
};

const Location = () => (
  <section style={{ background:"var(--cream)" }}>
    <div className="container">
      <header className="center reveal" style={{ maxWidth: 700, margin:"0 auto 48px" }}>
        <div className="eyebrow">Konum</div>
        <h2 style={{ margin:"14px 0 6px", font:'400 clamp(48px, 8vw, 78px)/.95 "Allura", cursive', color:"var(--coral)" }}>nasıl gelinir</h2>
      </header>
      <div className="loc-grid">
        <VenueMap/>
        <div className="card reveal" style={{ background:"#FFFCF7" }}>
          <h3 style={{ margin:"0 0 10px", font:'600 30px/1.1 "Cormorant Garamond", serif', color:"var(--coral)" }}>
            Kozlu Garden Düğün Salonu
          </h3>
          <p style={{ margin:"0 0 14px", color:"var(--ink)", lineHeight:1.6 }}>
            Merkez, Milli Egemenlik Cd.<br/>
            67600 Kozlu / Zonguldak<br/>
            <span style={{ color:"var(--muted)", fontStyle:"italic", fontSize: 15 }}>Kozlu Stadyumu'nun hemen yanında.</span>
          </p>
          <p style={{ margin:"0 0 22px" }}>
            <a href="tel:+903723456789" style={{ color:"var(--sage)", textDecoration:"none", fontWeight:600 }}>
              📞 +90 372 345 67 89
            </a>
          </p>
          <div style={{ display:"flex", gap: 10, flexWrap:"wrap" }}>
            <a className="btn btn-primary" href="https://maps.google.com/?q=Kozlu+Garden+D%C3%BC%C4%9F%C3%BCn+Salonu+Zonguldak" target="_blank" rel="noopener">
              🗺 Yol tarifi
            </a>
          </div>
        </div>
      </div>
    </div>
    <style>{`
      .loc-grid{ display:grid; grid-template-columns: 1fr; gap: 24px; }
      @media (min-width: 900px){ .loc-grid{ grid-template-columns: 1.2fr 1fr; gap: 36px; align-items: center; } }
    `}</style>
  </section>
);

/* ------------------- MESSAGE WALL ------------------- */


const colorMap = {
  peach:  { bg:"#FAD9C8", ink:"#7A4A3D" },
  sage:   { bg:"#E6E9DD", ink:"#5A6B47" },
  coral:  { bg:"#FBE6E2", ink:"#9C3E42" },
  cream:  { bg:"#F0E8DC", ink:"#5A4D3D" },
};

const PostIt = ({ msg, idx }) => {
  const c = colorMap[msg.color] || colorMap.peach;
  const rot = ((idx * 37) % 7) - 3; // -3 .. 3 deg
  return (
    <article style={{
      background: c.bg,
      color: c.ink,
      padding: "22px 22px 18px",
      borderRadius: "2px 14px 4px 12px",
      boxShadow:"0 14px 30px rgba(74,60,50,.14), 0 2px 6px rgba(74,60,50,.08)",
      transform:`rotate(${rot}deg)`,
      transition:"transform .3s ease, box-shadow .3s ease",
      position:"relative",
      minHeight: 140,
    }}
      onMouseEnter={(e)=> { e.currentTarget.style.transform = "rotate(0deg) translateY(-4px)"; }}
      onMouseLeave={(e)=> { e.currentTarget.style.transform = `rotate(${rot}deg)`; }}
    >
      <span style={{ position:"absolute", top:-6, right:14, opacity:.7 }}>
        <TinyFlower size={18} color={c.ink}/>
      </span>
      <p className="serif-i" style={{ margin:"0 0 14px", fontSize:18, lineHeight: 1.45, textWrap:"pretty" }}>
        “{msg.body}”
      </p>
      <div style={{ font:'600 13px/1 "Manrope", sans-serif', letterSpacing:".08em", textTransform:"uppercase", opacity:.85 }}>
        — {msg.name}
      </div>
    </article>
  );
};

const MessageWall = () => {
  const [msgs, setMsgs] = React.useState([]);
  const [shown, setShown] = React.useState(6);
  const [name, setName] = React.useState("");
  const [body, setBody] = React.useState("");
  const [honeypot, setHoneypot] = React.useState("");
  const [sending, setSending] = React.useState(false);

  React.useEffect(() => {
    const load = async () => {
      if (!window.SUPABASE_READY) return;
      const { data } = await window.supabaseClient
        .from('messages')
        .select('id, name, body, created_at')
        .eq('approved', true)
        .order('created_at', { ascending: false })
        .limit(50);
      if (data && data.length) {
        setMsgs(data.map((m, i) => ({ ...m, color: ['peach','sage','coral','cream'][i % 4] })));
      }
    };
    load();
  }, []);

  React.useEffect(() => {
    if (!window.SUPABASE_READY) return;
    const ch = window.supabaseClient
      .channel('messages-wall')
      .on('postgres_changes', { event: 'UPDATE', schema: 'public', table: 'messages', filter: 'approved=eq.true' }, (payload) => {
        const m = payload.new;
        setMsgs(prev => {
          if (prev.find(x => x.id === m.id)) return prev;
          const color = ['peach','sage','coral','cream'][prev.length % 4];
          return [{ ...m, color }, ...prev];
        });
      })
      .subscribe();
    return () => window.supabaseClient.removeChannel(ch);
  }, []);

  const submit = async (e) => {
    e.preventDefault();
    if (!name.trim() || !body.trim()) { toast("Adınızı ve mesajınızı yazar mısınız?"); return; }
    if (honeypot) return;
    setSending(true);
    try {
      const { error } = await window.supabaseClient.from('messages').insert({ name: name.trim(), body: body.trim(), honeypot: '' });
      if (error) throw error;
      toast("Mesajınız onay bekliyor 💕");
      setName(''); setBody('');
    } catch { toast("Bir sorun oluştu, lütfen tekrar deneyin 🙏"); }
    finally { setSending(false); }
  };

  return (
    <section id="mesaj" style={{ background:"var(--cream)", position:"relative" }}>
      <div className="container">
        <header className="center reveal" style={{ maxWidth: 700, margin:"0 auto 36px" }}>
          <div className="eyebrow">Bir Mesaj Bırakın</div>
          <h2 style={{ margin:"14px 0 0", font:'400 clamp(48px, 8vw, 78px)/.95 "Allura", cursive', color:"var(--coral)" }}>
            mesaj duvarı
          </h2>
          <p className="serif-i" style={{ color:"var(--muted)", marginTop: 6, fontSize: 18 }}>
            sen de bize bir mesaj bırak — bakarsın düğün günü yazdığını görürüz 💌
          </p>
        </header>

        <form onSubmit={submit} className="card reveal" style={{ background:"#FFFCF7", maxWidth: 760, margin:"0 auto 56px" }}>
          <input
            name="website" tabIndex="-1" autoComplete="off"
            value={honeypot} onChange={e => setHoneypot(e.target.value)}
            style={{ position:"absolute", left:"-9999px", width:1, height:1, opacity:0 }}
            aria-hidden="true"
          />
          <div className="msg-form-grid">
            <div>
              <label className="field-label" htmlFor="msg-name">Adınız</label>
              <input id="msg-name" className="input" value={name} onChange={e=>setName(e.target.value)} placeholder="ör. Ayşe" />
            </div>
            <div>
              <label className="field-label" htmlFor="msg-body">Mesajınız</label>
              <textarea id="msg-body" className="textarea" rows={3} value={body} onChange={e=>setBody(e.target.value)} placeholder="Birkaç güzel söz…" />
            </div>
          </div>
          <div style={{ display:"flex", justifyContent:"flex-end", marginTop: 16 }}>
            <button className="btn btn-primary" type="submit" disabled={sending} style={{ opacity: sending ? .7 : 1 }}>
              {sending ? "Gönderiliyor…" : "Mesajını paylaş 💌"}
            </button>
          </div>
        </form>

        {msgs.length === 0 ? (
          <p className="center serif-i" style={{ color:"var(--muted)", fontSize: 18, padding: "24px 0" }}>
            Henüz mesaj yok — ilk mesajı sen bırak 💕
          </p>
        ) : (
          <div className="msg-grid reveal">
            {msgs.slice(0, shown).map((m, i) => <PostIt key={m.id || i} msg={m} idx={i} />)}
          </div>
        )}
        {shown < msgs.length && (
          <div className="center" style={{ marginTop: 28 }}>
            <button className="btn btn-secondary" onClick={()=> setShown(n => n + 6)}>Daha fazla göster</button>
          </div>
        )}
      </div>
      <style>{`
        .msg-form-grid{ display:grid; grid-template-columns: 1fr; gap: 14px; }
        @media (min-width: 700px){ .msg-form-grid{ grid-template-columns: 1fr 2fr; gap: 18px; } }
        .msg-grid{ display:grid; grid-template-columns: 1fr; gap: 28px 22px; max-width: 1000px; margin: 0 auto; }
        @media (min-width: 640px){ .msg-grid{ grid-template-columns: 1fr 1fr; } }
        @media (min-width: 980px){ .msg-grid{ grid-template-columns: 1fr 1fr 1fr; } }
      `}</style>
    </section>
  );
};

/* ------------------- PHOTO UPLOAD CTA ------------------- */

const PhotoCTA = () => (
  <section style={{ background:"var(--cream)" }}>
    <div className="container reveal">
      <div style={{
        position:"relative",
        borderRadius: 32,
        padding: "44px 28px",
        background: "linear-gradient(135deg, #F4A5A0 0%, #FAD9C8 50%, #FBE6E2 100%)",
        boxShadow: "var(--shadow-3)",
        overflow:"hidden",
      }}>
        <div className="deco" style={{ top:-50, left:-60, opacity:.7 }}>
          <FloralCluster size={220} hue="peach" rotate={-30}/>
        </div>
        <div className="deco" style={{ bottom:-60, right:-60, opacity:.85 }}>
          <FloralCluster size={240} hue="coral" rotate={170}/>
        </div>

        <div className="cta-grid" style={{ position:"relative", zIndex:1 }}>
          <div>
            <div style={{ display:"inline-flex", alignItems:"center", gap:10, padding:"6px 14px", borderRadius:999, background:"rgba(250,245,239,.85)", color:"#9C3E42", font:'600 12px/1 "Manrope", sans-serif', letterSpacing:".22em", textTransform:"uppercase" }}>
              <span style={{ width:6, height:6, borderRadius:"50%", background:"#9C3E42" }}></span>
              04 Temmuz'da aktif
            </div>
            <h2 style={{
              margin:"16px 0 12px",
              font:'500 clamp(34px, 5vw, 52px)/1.05 "Cormorant Garamond", serif',
              color:"#fff",
              textShadow:"0 1px 1px rgba(0,0,0,.08)",
              textWrap:"balance",
            }}>
              Anılarımıza sen de katkıda bulun 📸
            </h2>
            <p style={{ margin:"0 0 22px", color:"#FAF5EF", fontSize: 16.5, lineHeight: 1.55, maxWidth: 520 }}>
              Düğün gecesi salondaki QR kodları telefonunla okutarak çektiğin fotoğrafları
              anında bu albüme yükleyebilirsin. Tek bir fotoğraf bile bizi çok mutlu eder.
            </p>
            <a className="btn" href="yukle.html" style={{ background:"#FAF5EF", color:"var(--coral)", boxShadow:"0 8px 22px rgba(74,60,50,.18)" }}>
              📤 Fotoğraf yükle
            </a>
          </div>
          <div style={{ display:"flex", justifyContent:"center", alignItems:"center" }}>
            <div style={{
              background:"#FAF5EF",
              padding: 18,
              borderRadius: 22,
              boxShadow:"0 16px 36px rgba(74,60,50,.2)",
              border:"2px solid #fff",
            }}>
              {/* Fake QR code visual */}
              <div style={{
                width: 180, height: 180,
                background: `
                  repeating-conic-gradient(#3E3B36 0% 25%, transparent 0% 50%) 0 0/14px 14px,
                  #FAF5EF
                `,
                borderRadius: 4,
                position:"relative",
                imageRendering:"pixelated",
              }}>
                {/* corner squares */}
                {["top:8px;left:8px","top:8px;right:8px","bottom:8px;left:8px"].map((p,i)=>(
                  <span key={i} style={{
                    position:"absolute", width:44, height:44,
                    background:"#FAF5EF", border:"6px solid #3E3B36", borderRadius:6,
                    ...(Object.fromEntries(p.split(";").map(s=>s.split(":").map(t=>t.trim())).map(([k,v])=>[k, v])))
                  }}/>
                ))}
              </div>
              <div style={{ textAlign:"center", marginTop: 10, font:'500 13px/1 "Manrope", sans-serif', letterSpacing:".15em", textTransform:"uppercase", color:"var(--coral)" }}>
                Telefonla okut
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <style>{`
      .cta-grid{ display:grid; grid-template-columns: 1fr; gap: 24px; }
      @media (min-width: 800px){ .cta-grid{ grid-template-columns: 1.4fr 1fr; gap: 36px; align-items: center; } }
    `}</style>
  </section>
);

/* ------------------- GALLERY PREVIEW ------------------- */

const PhotoThumb = ({ photo, idx }) => {
  const url = photo.thumbnail_url || photo.r2_url;
  const heights = [280,220,320,240,300,220,280,260,320];
  return (
    <div style={{
      borderRadius: 18, overflow:"hidden",
      height: heights[idx % heights.length],
      boxShadow: "var(--shadow-1)",
      position:"relative",
      transition:"transform .3s ease, box-shadow .3s ease",
      cursor:"zoom-in",
      background:"var(--cream-dark)",
    }}
      onMouseEnter={(e)=> { e.currentTarget.style.transform="translateY(-4px) scale(1.01)"; e.currentTarget.style.boxShadow="var(--shadow-2)"; }}
      onMouseLeave={(e)=> { e.currentTarget.style.transform=""; e.currentTarget.style.boxShadow="var(--shadow-1)"; }}
    >
      {photo.file_type === 'video' ? (
        <video src={url} style={{ width:"100%", height:"100%", objectFit:"cover" }} muted playsInline />
      ) : (
        <img src={url} alt={`Düğün anısı ${idx+1}`} style={{ width:"100%", height:"100%", objectFit:"cover", display:"block" }} loading="lazy" />
      )}
    </div>
  );
};

const GalleryPreview = () => {
  const [photos, setPhotos] = React.useState(null);

  React.useEffect(() => {
    const load = async () => {
      if (!window.SUPABASE_READY) { setPhotos([]); return; }
      const { data } = await window.supabaseClient
        .from('photos')
        .select('id, r2_url, thumbnail_url, file_type')
        .eq('approved', true)
        .order('created_at', { ascending: false })
        .limit(9);
      setPhotos(data || []);
    };
    load();
  }, []);

  return (
    <section style={{ background:"var(--cream-dark)" }}>
      <div className="container">
        <header className="center reveal" style={{ maxWidth: 700, margin:"0 auto 40px" }}>
          <div className="eyebrow">Misafir Galerisi</div>
          <h2 style={{ margin:"14px 0 6px", font:'400 clamp(48px, 8vw, 78px)/.95 "Allura", cursive', color:"var(--coral)" }}>
            ilk fotoğraflar
          </h2>
          <p className="serif-i" style={{ color:"var(--muted)", fontSize: 18, marginTop: 6 }}>
            düğün öncesi mod — gerçek anılar 4 Temmuz'da burada
          </p>
        </header>

        {photos === null ? (
          <p className="center serif-i" style={{ color:"var(--muted)", fontSize: 18, padding: "24px 0" }}>Yükleniyor…</p>
        ) : photos.length === 0 ? (
          <p className="center serif-i" style={{ color:"var(--muted)", fontSize: 18, padding: "24px 0" }}>
            Henüz fotoğraf yok — düğün günü burada görünecek 📸
          </p>
        ) : (
          <div className="reveal" style={{ columnCount: 2, columnGap: 16 }}>
            {photos.map((p, i) => (
              <div key={p.id} style={{ breakInside:"avoid", marginBottom: 16 }}>
                <PhotoThumb photo={p} idx={i} />
              </div>
            ))}
          </div>
        )}

        <div className="center" style={{ marginTop: 32 }}>
          <a className="btn btn-secondary" href="galeri.html">Tüm fotoğrafları gör →</a>
        </div>

        <style>{`
          @media (min-width: 700px){ section .reveal[style*="column-count"]{ column-count: 3; } }
          @media (min-width: 1000px){ section .reveal[style*="column-count"]{ column-count: 4; } }
        `}</style>
      </div>
    </section>
  );
};

/* ------------------- FAQ ------------------- */

const FAQItem = ({ q, a, open, onClick }) => (
  <div style={{
    borderRadius: 18,
    background: "#FFFCF7",
    border: "1px solid #E6E9DD",
    marginBottom: 12,
    overflow:"hidden",
    transition:"box-shadow .25s",
    boxShadow: open ? "var(--shadow-2)" : "var(--shadow-1)",
  }}>
    <button
      onClick={onClick}
      aria-expanded={open}
      style={{
        all:"unset",
        cursor:"pointer",
        display:"flex", justifyContent:"space-between", alignItems:"center",
        width:"100%",
        padding: "18px 22px",
        font:'500 18px/1.3 "Cormorant Garamond", serif',
        color:"var(--sage)",
        gap: 18,
      }}>
      <span style={{ textWrap:"pretty" }}>{q}</span>
      <span style={{
        flex:"0 0 28px",
        width:28, height:28, borderRadius:"50%",
        background:"#FBE6E2", color:"var(--coral)",
        display:"inline-flex", alignItems:"center", justifyContent:"center",
        transform:`rotate(${open?45:0}deg)`, transition:"transform .25s",
      }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 5v14M5 12h14"/></svg>
      </span>
    </button>
    <div style={{
      maxHeight: open ? 240 : 0,
      transition:"max-height .35s ease, padding .25s",
      overflow:"hidden",
    }}>
      <div style={{ padding:"0 22px 22px", color:"var(--muted)", lineHeight:1.65, fontSize: 15.5, textWrap:"pretty" }}>
        {a}
      </div>
    </div>
  </div>
);

const FAQ = () => {
  const [openIdx, setOpenIdx] = React.useState(0);
  const settings = useSettings();
  const faqs = settings.faq || [];
  return (
    <section style={{ background:"var(--cream)" }}>
      <div className="container" style={{ maxWidth: 820 }}>
        <header className="center reveal" style={{ marginBottom: 36 }}>
          <div className="eyebrow">SSS</div>
          <h2 style={{ margin:"14px 0 0", font:'400 clamp(48px, 8vw, 78px)/.95 "Allura", cursive', color:"var(--coral)" }}>
            sıkça sorulanlar
          </h2>
        </header>
        <div className="reveal">
          {faqs.map((f,i)=>(
            <FAQItem key={i} q={f.question} a={f.answer} open={openIdx===i} onClick={()=> setOpenIdx(openIdx===i ? -1 : i)} />
          ))}
        </div>
      </div>
    </section>
  );
};

/* ------------------- HOTELS ------------------- */

const Stars = ({ value }) => {
  const full = Math.floor(value);
  return (
    <span style={{ display:"inline-flex", gap: 2, color:"var(--sage)" }}>
      {Array.from({length:5}).map((_,i)=>(
        <svg key={i} width="14" height="14" viewBox="0 0 24 24"
             fill={i < full ? "currentColor" : (i < value ? "currentColor" : "none")}
             stroke="currentColor" strokeWidth="1.5"
             style={{ opacity: i < value ? 1 : .3 }}>
          <path d="M12 2l3.1 6.3 6.9 1L17 14.1l1.2 6.9L12 17.8 5.8 21l1.2-6.9L2 9.3l6.9-1L12 2z"/>
        </svg>
      ))}
      <span style={{ marginLeft: 6, font:'600 13px "Manrope", sans-serif', color:"var(--ink)" }}>{value.toFixed(1)}</span>
    </span>
  );
};

const Hotels = () => {
  const settings = useSettings();
  const hotels = settings.hotels || [];
  return (
    <section style={{ background:"var(--cream-dark)" }}>
      <div className="container">
        <header className="center reveal" style={{ maxWidth: 700, margin:"0 auto 40px" }}>
          <div className="eyebrow">Konaklama</div>
          <h2 style={{ margin:"14px 0 6px", font:'400 clamp(48px, 8vw, 78px)/.95 "Allura", cursive', color:"var(--coral)" }}>
            önerdiğimiz oteller
          </h2>
        </header>
        <div className="hotels-grid reveal">
          {hotels.map((h, i) => {
            const badge = parseBadge(h.badge, h.category);
            const res = h.category === 'general';
            return (
              <div key={i} className="card" style={{
                background: badge ? "#FDEFE6" : "#FFFCF7",
                border: badge ? "1px solid #F4A5A030" : "1px solid transparent",
                display:"flex", flexDirection:"column",
                position:"relative",
              }}>
                {badge && (
                  <span style={{
                    position:"absolute", top: 16, right: 16,
                    display:"inline-flex", alignItems:"center", gap: 6,
                    padding: "6px 12px", borderRadius: 999,
                    background: badge.bg, color: badge.fg,
                    font:'600 11.5px/1 "Manrope", sans-serif', letterSpacing:".06em",
                  }}>
                    <span aria-hidden="true">{badge.emoji}</span> {badge.label}
                  </span>
                )}
                <Stars value={h.rating} />
                <h3 style={{ margin:"10px 0 6px", font:'600 24px/1.2 "Cormorant Garamond", serif', color:"var(--coral)", paddingRight: badge ? 120 : 0 }}>{h.name}</h3>
                <div style={{ font:'500 13px/1 "Manrope", sans-serif', color:"var(--sage)", letterSpacing:".06em", marginBottom: 12 }}>
                  📍 salona ~{h.distance_km} km
                </div>
                <p style={{ margin:"0 0 16px", color:"var(--muted)", lineHeight: 1.55, fontSize: 15, textWrap:"pretty", flex:1 }}>{h.note}</p>
                {h.phone && (
                  <a href={`tel:${h.phone.replace(/\s/g,'')}`} style={{ color:"var(--sage)", fontWeight:600, textDecoration:"none", display:"inline-flex", alignItems:"center", gap:8, marginBottom: 16 }}>
                    📞 {h.phone}
                  </a>
                )}
                <div style={{ display:"flex", gap: 8, flexWrap:"wrap" }}>
                  <a className="btn btn-secondary" style={{ padding:"12px 18px", fontSize:14 }} href={`https://maps.google.com/?q=${encodeURIComponent(h.name + " Zonguldak")}`} target="_blank">Haritada gör</a>
                  {res && h.phone && <a className="btn btn-primary" style={{ padding:"12px 18px", fontSize:14 }} href={`tel:${h.phone.replace(/\s/g,'')}`}>Rezervasyon</a>}
                </div>
              </div>
            );
          })}
        </div>
        <div className="reveal" style={{ margin:"32px auto 0", maxWidth: 900, background:"#E6E9DD", border:"1px solid #5A6B4730", borderRadius: 18, padding:"18px 22px", display:"flex", alignItems:"flex-start", gap: 14 }}>
          <span style={{
            flex:"0 0 34px", width:34, height: 34, borderRadius:"50%",
            background:"#5A6B47", color:"#FAF5EF",
            display:"inline-flex", alignItems:"center", justifyContent:"center",
            font:'600 18px/1 "Cormorant Garamond", serif',
          }}>ℹ</span>
          <p style={{ margin:0, color:"var(--sage)", fontSize: 15, lineHeight: 1.6, textWrap:"pretty" }}>
            <strong style={{ color:"#3F4D32" }}>Bilgi:</strong> Kamu tesisleri (Öğretmenevi, Polisevi, Orduevi) için rezervasyonun 3–4 hafta önceden yapılması önerilir. Herhangi bir konuda damada ulaşabilirsiniz.
          </p>
        </div>
      </div>
      <style>{`
        .hotels-grid{ display:grid; grid-template-columns: 1fr; gap: 18px; }
        @media (min-width: 700px){ .hotels-grid{ grid-template-columns: 1fr 1fr; gap: 22px; } }
      `}</style>
    </section>
  );
};

/* ------------------- GIFT / IBAN ------------------- */

const IBANCard = ({ name, bank, iban }) => {
  const copy = async () => {
    try{
      await navigator.clipboard.writeText(iban.replace(/\s/g,''));
      toast("IBAN kopyalandı ✓");
    } catch { toast("Kopyalama başarısız oldu."); }
  };
  return (
    <div className="card" style={{
      background:"#FFFCF7",
      border:"1px double #F4A5A040",
      outline:"1px solid #F4A5A025",
      outlineOffset: "-6px",
      padding: "26px 24px",
    }}>
      <div style={{ font:'600 22px/1.2 "Cormorant Garamond", serif', color:"var(--coral)" }}>{name}</div>
      <div style={{ font:'500 13px/1 "Manrope", sans-serif', color:"var(--sage)", letterSpacing:".18em", textTransform:"uppercase", margin:"8px 0 16px" }}>
        {bank}
      </div>
      <div style={{
        font:'600 15px/1.4 ui-monospace, "SFMono-Regular", Menlo, monospace',
        color:"var(--sage)",
        background:"#F0E8DC",
        padding: "14px 16px",
        borderRadius: 12,
        wordBreak:"break-all",
        letterSpacing:".05em",
        marginBottom: 14,
      }}>
        {iban}
      </div>
      <button className="btn btn-secondary" onClick={copy} style={{ padding:"12px 18px", fontSize:14 }}>
        📋 IBAN'ı kopyala
      </button>
    </div>
  );
};

const Gift = () => {
  const settings = useSettings();
  const giftList = settings.gift || [];
  return (
    <section style={{ background:"var(--cream)" }}>
      <div className="container" style={{ maxWidth: 800 }}>
        <header className="center reveal" style={{ marginBottom: 32 }}>
          <div className="eyebrow">Hediye</div>
          <h2 style={{ margin:"14px 0 6px", font:'400 clamp(54px, 9vw, 92px)/.95 "Allura", cursive', color:"var(--coral)" }}>
            Varlığınız Yeter
          </h2>
          <p className="serif-i" style={{ color:"var(--muted)", maxWidth: 540, margin: "10px auto 0", fontSize: 18, lineHeight: 1.6, textWrap:"pretty" }}>
            Varlığınız bizim için en büyük hediye. Yine de katkıda bulunmak isteyenler için hesap bilgilerimiz aşağıdadır.
          </p>
        </header>
        <div className="iban-grid reveal">
          {giftList.map((g, i) => (
            <IBANCard key={i} name={g.holder} bank={g.bank} iban={g.iban} />
          ))}
        </div>
      </div>
      <style>{`
        .iban-grid{ display:grid; grid-template-columns: 1fr; gap: 18px; }
        @media (min-width: 700px){ .iban-grid{ grid-template-columns: 1fr 1fr; gap: 22px; } }
      `}</style>
    </section>
  );
};

/* ------------------- FOOTER ------------------- */

const Footer = () => (
  <footer style={{
    background: "linear-gradient(180deg, #4F5E40 0%, #3F4D32 100%)",
    color:"#FAF5EF",
    padding: "64px 0 32px",
    position:"relative",
    overflow:"hidden",
  }}>
    <div className="deco" style={{ top:-30, left:-40, opacity:.25 }}>
      <FloralCluster size={200} hue="coral" rotate={-30}/>
    </div>
    <div className="deco" style={{ bottom:-30, right:-40, opacity:.25 }}>
      <FloralCluster size={200} hue="peach" rotate={180}/>
    </div>

    <div className="container" style={{ position:"relative", zIndex:1 }}>
      <div className="foot-grid">
        <div>
          <div style={{ font:'400 clamp(48px, 7vw, 64px)/1 "Allura", cursive', color:"#F4A5A0" }}>
            Berat & Sude
          </div>
          <div className="eyebrow" style={{ color:"#FAD9C8", marginTop: 6 }}>04 Temmuz 2026</div>
          <p className="serif-i" style={{ color:"#FAF5EF", margin:"18px 0 0", fontSize: 18, opacity:.9, textWrap:"pretty" }}>
            Sizi düğünümüzde görmek için sabırsızlanıyoruz 💕
          </p>
        </div>
        <div>
          <div className="eyebrow" style={{ color:"#FAD9C8" }}>Hızlı linkler</div>
          <ul style={{ listStyle:"none", padding:0, margin:"16px 0 0", display:"grid", gap:10 }}>
            {[["#rsvp","Katılım Durumu"],["#mesaj","Mesaj Bırak"],["yukle.html","Fotoğraf Yükle"],["galeri.html","Galeri"],["#sss","SSS"]].map(([h,t])=>(
              <li key={t}><a href={h} style={{ color:"#FAF5EF", textDecoration:"none" }} onMouseEnter={e=>e.currentTarget.style.color="#F4A5A0"} onMouseLeave={e=>e.currentTarget.style.color="#FAF5EF"}>{t}</a></li>
            ))}
          </ul>
        </div>
        <div>
          <div className="eyebrow" style={{ color:"#FAD9C8" }}>İletişim</div>
          <ul style={{ listStyle:"none", padding:0, margin:"16px 0 0", display:"grid", gap:10, color:"#FAF5EF" }}>
            <li>Kozlu Garden, Zonguldak</li>
            <li><a href="tel:+903723456789" style={{ color:"inherit", textDecoration:"none" }}>📞 +90 372 345 67 89</a></li>
            <li style={{ opacity:.85, fontSize: 14 }}>Katılım için son tarih: 30 Haziran 2026</li>
          </ul>
        </div>
      </div>

      <div style={{
        margin:"40px auto 0",
        textAlign:"center",
        borderTop:"1px solid rgba(250,245,239,.18)",
        paddingTop: 22,
        fontSize: 13, opacity: .7
      }}>
        <span style={{ display:"inline-flex", alignItems:"center", gap: 10 }}>
          <TinyFlower size={14} color="#F4A5A0"/> sevgiyle hazırlandı · 2026 <TinyFlower size={14} color="#F4A5A0"/>
        </span>
      </div>
    </div>
    <style>{`
      .foot-grid{ display:grid; grid-template-columns: 1fr; gap: 32px; }
      @media (min-width: 800px){ .foot-grid{ grid-template-columns: 1.4fr 1fr 1fr; gap: 40px; } }
    `}</style>
  </footer>
);

Object.assign(window, {
  Hero, Welcome, ChildhoodPhotos, Story, Details, Location, MessageWall,
  PhotoCTA, GalleryPreview, FAQ, Hotels, Gift, Footer,
  useReveal, toast, launchConfetti
});
