/*  Multi-step Katılım Durumu (RSVP) — short form. */

const Step = ({ active, done, label }) => (
  <div style={{
    display:"flex", flexDirection:"column", alignItems:"center", gap: 8,
    flex: 1, position:"relative",
  }}>
    <span style={{
      width: 14, height: 14, borderRadius:"50%",
      background: active ? "#C9484D" : done ? "#5A6B47" : "#E6E9DD",
      border: active ? "3px solid #FBE6E2" : "3px solid transparent",
      boxShadow: active ? "0 0 0 2px #C9484D" : "none",
      transition:"all .3s ease",
    }}/>
    <span style={{
      font:'500 11px/1 "Manrope", sans-serif',
      letterSpacing:".15em",
      textTransform:"uppercase",
      color: active ? "var(--coral)" : done ? "var(--sage)" : "#B5AEA3",
      textAlign:"center",
    }}>{label}</span>
  </div>
);

const Steps = ({ idx, labels }) => (
  <div style={{
    display:"flex", alignItems:"flex-start", gap: 4,
    maxWidth: 460, margin:"0 auto 28px",
    position:"relative",
  }}>
    <div style={{
      position:"absolute", left: 24, right: 24, top: 6, height: 2,
      background:"#E6E9DD", zIndex: 0,
    }}/>
    <div style={{
      position:"absolute", left: 24, top: 6, height: 2,
      width: `calc(${(idx/(labels.length-1))*100}% - 24px)`,
      background:"var(--coral)",
      transition:"width .35s ease", zIndex: 0,
    }}/>
    {labels.map((l, i)=>(
      <div key={l} style={{ flex:1, position:"relative", zIndex:1 }}>
        <Step active={i===idx} done={i<idx} label={l}/>
      </div>
    ))}
  </div>
);

const Counter = ({ value, setValue, min=0, max=3, label }) => (
  <div>
    <label className="field-label">{label}</label>
    <div style={{ display:"flex", alignItems:"center", gap:14 }}>
      <button type="button" onClick={()=> setValue(Math.max(min, value-1))} style={btnRound} aria-label="azalt">−</button>
      <span style={{
        font:'600 28px/1 "Cormorant Garamond", serif',
        color:"var(--sage)",
        minWidth: 40, textAlign:"center",
        fontVariantNumeric:"tabular-nums",
      }}>{value}</span>
      <button type="button" onClick={()=> setValue(Math.min(max, value+1))} style={btnRound} aria-label="arttır">+</button>
    </div>
  </div>
);

const btnRound = {
  width: 44, height: 44, borderRadius: "50%",
  background:"#FBE6E2", color:"var(--coral)",
  border:"1.5px solid #F4A5A040",
  font:'500 22px/1 "Manrope", sans-serif',
  cursor:"pointer",
  transition:"all .2s",
};

/* segmented control */
const Seg = ({ value, setValue, options }) => (
  <div style={{ display:"grid", gridTemplateColumns: `repeat(${options.length}, 1fr)`, gap: 8 }}>
    {options.map(([v,l])=>(
      <button key={v} type="button" onClick={()=> setValue(v)} style={{
        all:"unset", cursor:"pointer",
        padding:"12px 14px",
        borderRadius: 12,
        border:"1.5px solid",
        borderColor: value===v ? "var(--coral)" : "var(--sage-bg)",
        background: value===v ? "#FBE6E2" : "transparent",
        color: value===v ? "var(--coral)" : "var(--ink)",
        font: '500 14.5px/1.2 "Manrope", sans-serif',
        textAlign:"center",
        transition:"all .2s",
      }}>{l}</button>
    ))}
  </div>
);

const RSVP = () => {
  const [step, setStep] = React.useState(0);
  const [coming, setComing] = React.useState(null);  // "yes" | "maybe" | "no"
  const [data, setData] = React.useState({
    name:"", email:"", phone:"",
    side: "",            // "gelin" | "damat"
    adults: 1, kids: 0,
    honeypot: "",        // bot trap — must stay empty
  });
  const [submitted, setSubmitted] = React.useState(false);
  const [loading, setLoading] = React.useState(false);

  const set = (k,v) => setData(d => ({...d, [k]:v}));

  // 3 steps: Cevap → Bilgiler → Özet
  const labels = ["Cevap", "Bilgiler", "Özet"];
  const max = labels.length;

  const next = () => setStep(s => Math.min(s+1, max-1));
  const back = () => setStep(s => Math.max(0, s-1));

  const submit = async () => {
    if (data.honeypot) return; // bot
    setLoading(true);
    try {
      const { error } = await window.supabaseClient.from('rsvps').insert({
        full_name: data.name,
        phone: data.phone || null,
        side: data.side || null,
        status: coming,
        adult_count: data.adults,
        children_count: data.kids,
        allergies: null,
        song_request: null,
        message: null,
        honeypot: data.honeypot,
      });
      if (error) throw error;
      setSubmitted(true);
      launchConfetti();
      setTimeout(launchConfetti, 600);
    } catch (err) {
      console.error('RSVP submit error:', err);
      toast("Bir sorun oluştu, lütfen tekrar deneyin 🙏");
    } finally {
      setLoading(false);
    }
  };

  const isComing = coming === "yes" || coming === "maybe";

  if (submitted){
    return (
      <section id="rsvp" style={{ background:"var(--cream)" }}>
        <div className="container" style={{ maxWidth: 720 }}>
          <div className="card center" style={{ background:"#FFFCF7", padding: "52px 32px" }}>
            <div style={{ marginBottom: 18 }}>
              <FloralCluster size={120} hue="coral" rotate={0} style={{ display:"inline-block" }}/>
            </div>
            <h2 style={{ margin:"0 0 12px", font:'400 clamp(40px, 7vw, 64px)/1 "Allura", cursive', color:"var(--coral)" }}>
              Teşekkürler!
            </h2>
            <p className="serif-i" style={{ fontSize: 22, color:"var(--sage)", margin: 0, textWrap:"pretty" }}>
              {coming === "yes"   && "Sizi orada görmek için sabırsızlanıyoruz 💕"}
              {coming === "maybe" && "Bizi bilgilendirdiğiniz için teşekkürler — gelebilirseniz çok seviniriz 💕"}
              {coming === "no"    && "Bizi haberdar ettiğiniz için teşekkür ederiz. Sizi özleyeceğiz 🌿"}
            </p>
            <button className="btn btn-secondary" style={{ marginTop: 26 }} onClick={()=>{ setSubmitted(false); setStep(0); setComing(null); }}>
              Cevabı düzenle
            </button>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section id="rsvp" style={{ background:"var(--cream)", position:"relative" }}>
      <div className="deco" style={{ top:40, left:-40, opacity:.55 }}>
        <FloralCluster size={170} hue="peach" rotate={-30}/>
      </div>
      <div className="deco" style={{ bottom:30, right:-40, opacity:.55 }}>
        <FloralCluster size={170} hue="coral" rotate={140}/>
      </div>

      <div className="container" style={{ maxWidth: 720 }}>
        <header className="center reveal" style={{ marginBottom: 32 }}>
          <div className="eyebrow">Katılım Durumu</div>
          <h2 style={{ margin:"14px 0 6px", font:'400 clamp(48px, 8vw, 78px)/.95 "Allura", cursive', color:"var(--coral)" }}>
            Bizimle olur musunuz? 💕
          </h2>
          <p className="serif-i" style={{ color:"var(--muted)", marginTop: 6, fontSize: 17 }}>
            cevabınız için son tarih: 30 Haziran 2026
          </p>
        </header>

        <div className="card reveal" style={{ background:"#FFFCF7", padding: "30px 26px 26px" }}>
          <Steps idx={step} labels={labels}/>

          {/* ---- Step 0: yes / maybe / no ---- */}
          {step === 0 && (
            <div style={{ display:"grid", gap: 12, marginTop: 14 }}>
              <p className="center serif-i" style={{ margin:"0 0 8px", fontSize: 20, color:"var(--sage)" }}>
                Düğünümüze katılabilecek misiniz?
              </p>
              <button className="btn btn-primary" style={{ padding:"20px 22px", fontSize: 17 }}
                onClick={()=> { setComing("yes"); next(); }}>
                ✅ Evet, oradayız!
              </button>
              <button className="btn" style={{
                padding:"18px 22px", fontSize: 16,
                background:"#F4A5A0", color:"#fff",
                boxShadow:"0 6px 14px rgba(244,165,160,.3)",
              }} onClick={()=> { setComing("maybe"); next(); }}>
                🤞 Gelmeye çalışacağım
              </button>
              <button className="btn btn-secondary" style={{ padding:"18px 22px", fontSize: 16 }}
                onClick={()=> { setComing("no"); next(); }}>
                😢 Maalesef gelemeyeceğim
              </button>
            </div>
          )}

          {/* ---- Step 1: info ---- */}
          {step === 1 && (
            <div style={{ display:"grid", gap: 16, marginTop: 14 }}>
              <div>
                <label className="field-label" htmlFor="r-name">Ad Soyad <span style={{ color:"var(--coral)" }}>*</span></label>
                <input id="r-name" className="input" value={data.name} onChange={e=>set("name",e.target.value)} placeholder="ör. Ayşe Yılmaz"/>
              </div>

              <div>
                <label className="field-label">Hangi taraftan?</label>
                <Seg value={data.side} setValue={v=>set("side",v)} options={[["gelin","Gelin tarafı"],["damat","Damat tarafı"]]} />
              </div>

              <div>
                <label className="field-label" htmlFor="r-phone">Telefon <span style={{ opacity:.6 }}>(opsiyonel)</span></label>
                <input id="r-phone" className="input" type="tel" inputMode="tel" value={data.phone} onChange={e=>set("phone",e.target.value)} placeholder="telefon"/>
              </div>

              {isComing && (
                <div className="rsvp-2col">
                  <Counter value={data.adults} setValue={v=>set("adults",v)} min={1} max={3} label="Yetişkin"/>
                  <Counter value={data.kids}   setValue={v=>set("kids",v)}   min={0} max={3} label="Çocuk"/>
                </div>
              )}

              <div style={navStyle}>
                <button className="btn btn-ghost" onClick={back}>← Geri</button>
                <button className="btn btn-primary" onClick={()=> {
                  if (!data.name.trim()) { toast("Adınızı yazar mısınız?"); return; }
                  if (!data.side) { toast("Gelin mi damat tarafındansınız? Lütfen seçiniz."); return; }
                  next();
                }}>Devam</button>
              </div>
            </div>
          )}

          {/* ---- Step 2: summary ---- */}
          {step === 2 && (
            <div style={{ marginTop: 14 }}>
              <p className="serif-i center" style={{ margin:"0 0 16px", fontSize: 18, color:"var(--sage)" }}>
                Cevabınızı gönderelim mi?
              </p>
              <div style={{
                background:"#F0E8DC",
                borderRadius: 18,
                padding: "20px 22px",
                display:"grid", gap: 10,
              }}>
                <SummaryRow k="Cevap" v={
                  coming === "yes"   ? "Geliyorum ✅" :
                  coming === "maybe" ? "Gelmeye çalışacağım 🤞" :
                                       "Maalesef gelemeyeceğim 😢"
                } />
                <SummaryRow k="Ad Soyad" v={data.name || "—"} />
                {data.side  && <SummaryRow k="Taraf"   v={data.side === "gelin" ? "Gelin tarafı" : "Damat tarafı"}/>}
                {data.phone && <SummaryRow k="Telefon" v={data.phone}/>}
                {isComing && <>
                  <SummaryRow k="Yetişkin" v={data.adults}/>
                  <SummaryRow k="Çocuk"    v={data.kids}/>
                </>}
              </div>
              {/* honeypot — hidden from real users */}
              <input
                name="website"
                tabIndex="-1"
                autoComplete="off"
                value={data.honeypot}
                onChange={e => set("honeypot", e.target.value)}
                style={{ position:"absolute", left:"-9999px", width:1, height:1, opacity:0 }}
                aria-hidden="true"
              />
              <div style={{...navStyle, marginTop: 22}}>
                <button className="btn btn-ghost" onClick={back} disabled={loading}>← Geri</button>
                <button
                  className="btn btn-primary"
                  onClick={submit}
                  disabled={loading}
                  style={{ minWidth: 180, opacity: loading ? .7 : 1 }}
                >
                  {loading ? "Gönderiliyor…" : "Gönder 💌"}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
      <style>{`
        .rsvp-2col{ display:grid; grid-template-columns: 1fr 1fr; gap: 18px; }
        @media (max-width: 560px){
          .rsvp-2col{ grid-template-columns: 1fr; gap: 14px; }
        }
      `}</style>
    </section>
  );
};

const SummaryRow = ({ k, v }) => (
  <div style={{ display:"grid", gridTemplateColumns:"110px 1fr", gap: 14, alignItems:"baseline" }}>
    <span style={{ font:'500 12px/1 "Manrope", sans-serif', letterSpacing:".18em", textTransform:"uppercase", color:"var(--sage)"}}>{k}</span>
    <span style={{ font:'500 17px/1.3 "Cormorant Garamond", serif', color:"var(--ink)", textWrap:"pretty" }}>{v}</span>
  </div>
);

const navStyle = { display:"flex", justifyContent:"space-between", alignItems:"center", marginTop: 18 };

Object.assign(window, { RSVP });
