/* global React, ReactDOM, TweaksPanel, useTweaks, TweakSection, TweakRadio, TweakText */
const { useState, useEffect, useMemo } = React;

const G_DEFAULTS = /*EDITMODE-BEGIN*/{
  "groomShort": "Thái Bảo",
  "brideShort": "Thiên An",
  "year": "2026",
  "groomSaint": "Anphong Maria",
  "groomName": "Lương Thái Bảo",
  "groomRole": "Trưởng Nam",
  "brideSaint": "Anna",
  "brideName": "Trần Thiên An",
  "brideRole": "Trưởng Nữ",
  "groomFather": "Ông Lương Văn Hùng",
  "groomMother": "Bà Lê Thị Mai",
  "groomAddress": "Nguyễn Văn Tạo, Hiệp Phước, TP. Hồ Chí Minh",
  "brideFather": "Ông Trần Văn Bình",
  "brideMother": "Bà Phạm Thị Lan",
  "brideAddress": "Tổ 9, Ngọc Lâm 5, P. Tân Phú, TP. Đồng Nai",
  "ceremonyPlace": "Tư Gia",
  "ceremonyTime": "16 giờ 00",
  "ceremonyWeekday": "Thứ Năm",
  "ceremonyDate": "Ngày 25 tháng 06 năm 2026",
  "lunar": "Nhằm ngày 11 tháng 05 năm Bính Ngọ",
  "receiverName": "Quý Khách",
  "receptionVenue": "Nhà Hàng Biển Nhớ 2",
  "receptionAddress": "583/1 Nguyễn Bình - Ấp 1, Xã Hiệp Phước - TP. Hồ Chí Minh",
  "receptionWeekday": "Thứ Năm",
  "receptionTime": "18 giờ 00",
  "receptionDate": "Ngày 25.06.2026",
  "welcomeTime": "18:00",
  "feastTime": "18:30",
  "accent": "sage"
}/*EDITMODE-END*/;

// ---------- Guest list (via /api/guest, edge-cached) ----------
async function resolveGuestName(id) {
  const res = await fetch(`/api/guest?id=${encodeURIComponent(id)}`);
  if (!res.ok) return null;
  const { name } = await res.json();
  return name;
}

// ---------- Botanical line art ----------
function Sprig({ size = 26, flip }) {
  return (
    <svg width={size} height={size} viewBox="0 0 26 26" fill="none" aria-hidden="true"
         style={flip ? { transform: "scaleX(-1)" } : null}>
      <path d="M13 25 C13 16 13 9 13 2" stroke="currentColor" strokeWidth="1" strokeLinecap="round"/>
      {[6,11,16].map((y,i) => (
        <g key={i}>
          <path d={`M13 ${y} C9 ${y-2} 6 ${y-1} 5 ${y+2} C8 ${y+3} 11 ${y+2} 13 ${y}`} fill="currentColor" opacity=".5"/>
          <path d={`M13 ${y+2} C17 ${y} 20 ${y+1} 21 ${y+4} C18 ${y+5} 15 ${y+4} 13 ${y+2}`} fill="currentColor" opacity=".5"/>
        </g>
      ))}
    </svg>
  );
}

function Wreath({ size = 76 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 76 76" fill="none" aria-hidden="true">
      <g stroke="currentColor" strokeWidth="1">
        <path d="M38 66 C20 62 12 48 14 32" fill="none"/>
        <path d="M38 66 C56 62 64 48 62 32" fill="none"/>
      </g>
      {Array.from({length: 6}).map((_, i) => {
        const t = i / 5, a = Math.PI * (0.62 + t * 0.46);
        const x = 38 + Math.cos(a) * 26, y = 49 - Math.sin(a) * 26;
        return <ellipse key={"l"+i} cx={x} cy={y} rx="5" ry="2.4" fill="currentColor" opacity=".5"
                        transform={`rotate(${-a*180/Math.PI+90} ${x} ${y})`} />;
      })}
      {Array.from({length: 6}).map((_, i) => {
        const t = i / 5, a = Math.PI * (0.38 - t * 0.46);
        const x = 38 + Math.cos(a) * 26, y = 49 - Math.sin(a) * 26;
        return <ellipse key={"r"+i} cx={x} cy={y} rx="5" ry="2.4" fill="currentColor" opacity=".5"
                        transform={`rotate(${-a*180/Math.PI+90} ${x} ${y})`} />;
      })}
      <circle cx="38" cy="22" r="3.4" fill="var(--blush)" opacity=".8" />
    </svg>
  );
}

function Rings() {
  return (
    <svg width="54" height="30" viewBox="0 0 54 30" fill="none" aria-hidden="true">
      <ellipse cx="22" cy="17" rx="9" ry="10" stroke="currentColor" strokeWidth="1.4"/>
      <ellipse cx="32" cy="17" rx="9" ry="10" stroke="currentColor" strokeWidth="1.4"/>
      <path d="M19 7 l3 -4 l3 4" stroke="currentColor" strokeWidth="1.2" fill="none"/>
    </svg>
  );
}

function SprigRow() {
  return (
    <div className="sprig-row">
      <span className="ln" />
      <span style={{transform:"rotate(-90deg)"}}><Sprig size={22} /></span>
      <span style={{transform:"rotate(90deg)"}}><Sprig size={22} /></span>
      <span className="ln r" />
    </div>
  );
}

// ---------- Photo + reveal ----------
function Photo({ id, placeholder, className }) {
  return (
    <div className={"photo " + (className || "")}>
      <image-slot id={id} placeholder={placeholder || "Thả ảnh vào đây"} shape="rect"></image-slot>
    </div>
  );
}
function useReveal(active) {
  useEffect(() => {
    if (!active) return;
    const els = document.querySelectorAll(".reveal, .reveal-z");
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { e.target.classList.add("in"); io.unobserve(e.target); } });
    }, { threshold: 0.12, rootMargin: "0px 0px -7% 0px" });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, [active]);
}

// ---------- Letter ----------
function Letter({ t, receiver, guestLoading, onOpen, opening }) {
  return (
    <div className={"stage-letter" + (opening ? " opening" : "")}>
      <div className="letter">
        <span className="wash a" /><span className="wash b" />
        <div className="wreath sway"><Wreath /></div>
        <div className="label">Save the date</div>
        <h1 className="display">
          {t.groomShort}<br/><span className="amp">♥</span><br/>{t.brideShort}
        </h1>
        <p className="lead">
          Trong niềm hân hoan, chúng tôi trân trọng báo tin ngày vui của hai con —
          và rất mong được đón tiếp quý vị.
        </p>
        <div className="when">
          {t.receptionDate.replace(/^Ngày\s*/i, "")}
          <span className="dot">✿</span> {t.lunar.replace(/^Nhằm\s*/i, "")}
        </div>
        <div className="letter-invite">
          Trân trọng kính mời<br/>
          <span className={"letter-receiver" + (guestLoading ? " is-loading" : "")}>
            {guestLoading ? "Đang tải…" : receiver}
          </span>
        </div>
        <button className="btn btn-primary" onClick={onOpen}>Mở Thiệp Mời</button>
      </div>
    </div>
  );
}

// ---------- Section 1 — Báo hỷ ----------
function Section1Hero({ t }) {
  return (
    <section className="bloc" style={{paddingTop: 92}}>
      <div className="container hero">
        <div className="reveal" style={{color:"var(--sage-deep)", marginBottom: 8}}><Wreath size={64} /></div>

        <div className="vn-parents reveal">
          <div className="vn-side">
            <div className="side-label">Nhà Trai</div>
            <div className="nm">{t.groomFather}<br/>{t.groomMother}</div>
            <div className="addr">{t.groomAddress}</div>
          </div>
          <div className="vn-side">
            <div className="side-label">Nhà Gái</div>
            <div className="nm">{t.brideFather}<br/>{t.brideMother}</div>
            <div className="addr">{t.brideAddress}</div>
          </div>
        </div>

        <p className="announce reveal">Trân trọng báo tin Lễ Thành Hôn<br/>của con chúng tôi</p>

        <div className="formal reveal">
          <div className="saint">{t.groomSaint}</div>
          <div className="full">{t.groomName}</div>
          <div className="role">{t.groomRole}</div>
        </div>
        <div className="rings reveal"><Rings /></div>
        <div className="formal reveal">
          <div className="saint">{t.brideSaint}</div>
          <div className="full">{t.brideName}</div>
          <div className="role">{t.brideRole}</div>
        </div>

        <div className="ceremony-vn reveal">
          <SprigRow />
          <div>Hôn lễ được cử hành tại <span className="strong">{t.ceremonyPlace}</span></div>
          <div className="big">Vào lúc {t.ceremonyTime} · {t.ceremonyWeekday}</div>
          <div className="big">{t.ceremonyDate}</div>
          <div className="lunar">({t.lunar})</div>
        </div>
      </div>
    </section>
  );
}

// ---------- Section 2 — Tiệc cưới ----------
function Section2Reception({ t, receiver, guestLoading }) {
  return (
    <section className="bloc">
      <div className="container narrow">
        <div className="rcard reveal-z">
          <span className="wash a" /><span className="wash b" />
          <div className="welcome-kicker">Welcome to our wedding</div>
          <div className="welcome-names">{t.groomShort} ♥ {t.brideShort}</div>
          <div className="label" style={{marginTop: 10}}>Trân trọng kính mời</div>
          <div className="receiver">
            <span className={"receiver-name" + (guestLoading ? " is-loading" : "")}>
              {guestLoading ? "Đang tải…" : receiver}
            </span>
          </div>
          <p className="invite">đến dự buổi tiệc chung vui cùng gia đình chúng tôi tại</p>
          <h3 className="venue-name">{t.receptionVenue}</h3>
          <div className="addr">{t.receptionAddress}</div>
          <div className="when-pill">
            <span>{t.receptionWeekday} · {t.receptionTime}</span>
            <span className="sep">✿</span>
            <span>{t.receptionDate}</span>
          </div>
          <div className="lunar" style={{fontStyle:"italic", color:"var(--ink-2)", fontSize:15, marginTop:10}}>
            ({t.lunar})
          </div>
          <p className="present-note">
            Sự hiện diện của quý khách<br/>là niềm vinh hạnh cho gia đình chúng tôi
          </p>
          <div className="events">
            <div className="ev"><div className="t">{t.welcomeTime}</div><div className="l">Đón khách</div></div>
            <div className="div" />
            <div className="ev"><div className="t">{t.feastTime}</div><div className="l">Khai tiệc</div></div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- Section 3 — Timeline ----------
const TIMELINE = {
  "24.06 — Trước Lễ": [
    { time: "15:00", ap: "Chiều", title: "Trang hoàng tư gia", note: "Gia đình cùng nhau chuẩn bị, kết hoa và bày biện cho ngày trọng đại." },
    { time: "17:00", ap: "Chiều", title: "Lễ gia tiên", note: "Dâng hương kính báo tổ tiên trong không khí ấm cúng." },
    { time: "19:00", ap: "Tối", title: "Tiệc thân mật", note: "Bữa cơm sum vầy cùng họ hàng và bạn bè thân thiết ở xa về." },
  ],
  "25.06 — Ngày Trọng Đại": [
    { time: "16:00", ap: "Chiều", title: "Hôn lễ tại tư gia", note: "Hai con chính thức nên duyên vợ chồng trước sự chứng kiến của hai họ." },
    { time: "17:00", ap: "Chiều", title: "Chụp ảnh lưu niệm", note: "Cùng lưu giữ những khoảnh khắc đẹp bên gia đình và bạn bè." },
    { time: "18:00", ap: "Tối", title: "Đón khách", note: "Kính mời quý khách đến Nhà Hàng Biển Nhớ 2." },
    { time: "18:30", ap: "Tối", title: "Khai tiệc", note: "Bữa tiệc chung vui chính thức bắt đầu." },
    { time: "20:00", ap: "Tối", title: "Cắt bánh & nâng ly", note: "Khoảnh khắc ngọt ngào và lời chúc phúc từ mọi người." },
    { time: "21:00", ap: "Tối", title: "Tiễn khách", note: "Cảm ơn quý khách đã đến chung vui cùng gia đình." },
  ]
};
function Section3Timeline() {
  const days = Object.keys(TIMELINE);
  const [active, setActive] = useState(days[1]);
  return (
    <section className="bloc">
      <div className="container">
        <div className="sec-head reveal">
          <span className="label">Chương Trình</span>
          <h2>Hai Ngày Trọng Đại</h2>
          <p className="sub">đôi dòng lịch trình cho ngày vui</p>
        </div>
        <div style={{textAlign:"center"}}>
          <div className="day-toggle">
            {days.map(d => (
              <button key={d} className={active===d?"active":""} onClick={() => setActive(d)}>{d}</button>
            ))}
          </div>
        </div>
        <div className="tl">
          {TIMELINE[active].map((it, i) => (
            <div className="tl-row reveal" key={active+i}>
              <div className="tl-time">{it.time}<span className="ap">{it.ap}</span></div>
              <div className="tl-card">
                <h4>{it.title}</h4>
                <p>{it.note}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- Section 4 — Chuyện tình ----------
const STORY = [
  { n: "i",   when: "2017 · Lần đầu gặp gỡ", title: "Định mệnh sắp đặt", body: "Một buổi chiều tình cờ, hai người gặp nhau trong một dịp họp mặt. Một ánh nhìn, một nụ cười — và câu chuyện của chúng mình bắt đầu từ đó." },
  { n: "ii",  when: "2019 · Cùng nhau đi", title: "Những chuyến đi đầu tiên", body: "Chúng mình cùng nhau khám phá những vùng đất mới, học cách lắng nghe và sẻ chia. Mỗi chuyến đi là một mảnh ghép của yêu thương." },
  { n: "iii", when: "2024 · Lời cầu hôn", title: "Câu hỏi của cả đời", body: "Dưới ánh đèn ấm áp, anh đã hỏi câu hỏi quan trọng nhất. Và em đã mỉm cười gật đầu — bắt đầu cho một hành trình mới." },
  { n: "iv",  when: "2026 · Và bây giờ", title: "Mong có quý vị chung vui", body: "Mọi câu chuyện đẹp đều cần những người thân yêu cùng góp mặt. Chuyện của chúng mình đã có ngày, có nơi, và một chỗ dành riêng cho quý vị." },
];
function Section4Story() {
  return (
    <section className="bloc">
      <div className="container">
        <div className="sec-head reveal">
          <span className="label">Hành Trình Yêu Thương</span>
          <h2>Chuyện Tình Chúng Mình</h2>
          <p className="sub">kể qua bốn mùa thương nhớ</p>
        </div>
        <div className="story">
          {STORY.map((s, i) => (
            <div className={"srow reveal" + (i % 2 ? " flip" : "")} key={i}>
              <div className="stext">
                <div className="snum">{s.n}</div>
                <div className="when">{s.when}</div>
                <h3>{s.title}</h3>
                <p>{s.body}</p>
              </div>
              <Photo id={"g-story-" + i} placeholder={"Ảnh · " + s.title} />
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- Gallery ----------
const GALLERY = [
  { id: "g-ga", cls: "ga", ph: "Ảnh yêu thích" },
  { id: "g-gb", cls: "gb", ph: "Khoảnh khắc đời thường" },
  { id: "g-gc", cls: "gc", ph: "Trong vườn" },
  { id: "g-gd", cls: "gd", ph: "Ngày cầu hôn" },
  { id: "g-ge", cls: "ge", ph: "Chỉ hai chúng mình" },
];
function SectionGallery() {
  return (
    <section className="bloc">
      <div className="container">
        <div className="sec-head reveal">
          <span className="label">Album Của Chúng Mình</span>
          <h2>Khoảnh Khắc</h2>
          <p className="sub">thả ảnh của bạn vào từng khung hình</p>
        </div>
        <div className="gallery reveal-z">
          {GALLERY.map(g => <Photo key={g.id} id={g.id} className={g.cls} placeholder={g.ph} />)}
        </div>
      </div>
    </section>
  );
}

// ---------- QR ----------
function QR() {
  const N = 25;
  const cells = useMemo(() => {
    const grid = Array.from({ length: N }, () => Array(N).fill(0));
    const finder = (r, c) => {
      for (let y = 0; y < 7; y++) for (let x = 0; x < 7; x++) {
        const edge = x === 0 || x === 6 || y === 0 || y === 6;
        const core = x >= 2 && x <= 4 && y >= 2 && y <= 4;
        grid[r + y][c + x] = (edge || core) ? 1 : 0;
      }
    };
    finder(0, 0); finder(0, N - 7); finder(N - 7, 0);
    for (let i = 8; i < N - 8; i++) { grid[6][i] = i % 2 === 0 ? 1 : 0; grid[i][6] = i % 2 === 0 ? 1 : 0; }
    const ar = N - 9, ac = N - 9;
    for (let y = 0; y < 5; y++) for (let x = 0; x < 5; x++) {
      const e = x === 0 || x === 4 || y === 0 || y === 4, c = x === 2 && y === 2;
      grid[ar + y][ac + x] = (e || c) ? 1 : 0;
    }
    const rand = (i) => (Math.sin(i * 99.13) + 1) / 2;
    for (let y = 0; y < N; y++) for (let x = 0; x < N; x++) {
      const reserved = (y < 8 && x < 8) || (y < 8 && x >= N - 8) || (y >= N - 8 && x < 8)
        || (y >= ar && y < ar + 5 && x >= ac && x < ac + 5) || y === 6 || x === 6;
      if (!reserved) grid[y][x] = rand(y * N + x) > 0.5 ? 1 : 0;
    }
    return grid.flat();
  }, []);
  return (
    <div style={{ display: "grid", gridTemplateColumns: `repeat(${N},1fr)`, gap: 0, width: 200, height: 200 }}>
      {cells.map((on, i) => <div key={i} style={{ background: on ? "var(--ink)" : "transparent" }} />)}
    </div>
  );
}

function RsvpModal({ open, onClose, defaultName, onSubmit }) {
  const [name, setName] = useState(defaultName || "");
  const [response, setResponse] = useState("yes");
  const [guests, setGuests] = useState(2);
  const [note, setNote] = useState("");
  const [done, setDone] = useState(false);
  useEffect(() => { if (open) { setDone(false); setName(defaultName || ""); } }, [open, defaultName]);
  if (!open) return null;
  const submit = (e) => { e.preventDefault(); onSubmit && onSubmit({name,response,guests,note}); setDone(true); };
  return (
    <div className="modal-bg" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <button className="close" onClick={onClose} aria-label="Đóng">×</button>
        {!done ? (
          <>
            <span className="label">Phản hồi</span>
            <h3>Quý khách có tham dự?</h3>
            <p>Mong nhận được phản hồi trước ngày 01.06.</p>
            <form onSubmit={submit}>
              <div className="field">
                <label>Tên của bạn</label>
                <input value={name} onChange={e => setName(e.target.value)} required />
              </div>
              <div className="field">
                <label>Bạn có đến chung vui?</label>
                <select value={response} onChange={e => setResponse(e.target.value)}>
                  <option value="yes">Vui lòng tham dự</option>
                  <option value="maybe">Có thể — sẽ xác nhận sau</option>
                  <option value="no">Rất tiếc không thể đến</option>
                </select>
              </div>
              <div className="field">
                <label>Số người tham dự</label>
                <input type="number" min="0" max="10" value={guests} onChange={e => setGuests(+e.target.value)} />
              </div>
              <div className="field"><label>Lời nhắn gửi cô dâu chú rể</label>
                <textarea rows="2" value={note} onChange={e => setNote(e.target.value)} placeholder="Không bắt buộc" /></div>
              <button className="btn btn-primary" type="submit" style={{width:"100%", justifyContent:"center"}}>Gửi phản hồi</button>
            </form>
          </>
        ) : (
          <div className="confirm">
            <div className="ring">
              <svg width="26" height="26" viewBox="0 0 26 26" fill="none"><path d="M6 13 L11 18 L20 7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </div>
            <h3>Cảm ơn {name.trim() || "bạn"}.</h3>
            <p style={{marginBottom: 18}}>
              {response==="yes" && "Gia đình rất hân hạnh được đón tiếp quý khách!"}
              {response==="maybe" && "Chúng tôi sẽ giữ một chỗ chờ quý khách."}
              {response==="no" && "Thật tiếc — gia đình vẫn xin gửi lời cảm ơn chân thành."}
            </p>
            <button className="btn btn-ghost" onClick={onClose}>Đóng</button>
          </div>
        )}
      </div>
    </div>
  );
}

function Section5Rsvp({ receiver }) {
  const [open, setOpen] = useState(false);
  return (
    <section className="bloc">
      <div className="container narrow rsvp">
        <div className="sec-head reveal">
          <span className="label">Xác Nhận Tham Dự</span>
          <h2>Quý khách có đến chung vui?</h2>
          <p className="sub">quét mã, hoặc phản hồi bên dưới — trước ngày 01.06</p>
        </div>
        <div className="qr-card reveal-z">
          <div className="qr-inner"><QR /></div>
          <div className="italic">quét mã để phản hồi từ điện thoại</div>
        </div>
        <div className="rsvp-actions">
          <button className="btn btn-primary" onClick={() => setOpen(true)}>Vui lòng tham dự</button>
          <button className="btn btn-ghost" onClick={() => setOpen(true)}>Xin phép vắng mặt</button>
        </div>
      </div>
      <RsvpModal open={open} onClose={() => setOpen(false)} defaultName={receiver}
                 onSubmit={(d) => console.log("RSVP:", d)} />
    </section>
  );
}

// ---------- Tweaks ----------
function GardenTweaks({ t, setTweak }) {
  return (
    <TweaksPanel title="Tuỳ Chỉnh">
      <TweakSection title="Cô Dâu & Chú Rể">
        <TweakText label="Tên gọi chú rể" value={t.groomShort} onChange={v => setTweak("groomShort", v)} />
        <TweakText label="Tên gọi cô dâu" value={t.brideShort} onChange={v => setTweak("brideShort", v)} />
        <TweakText label="Tên thánh chú rể" value={t.groomSaint} onChange={v => setTweak("groomSaint", v)} />
        <TweakText label="Họ tên chú rể" value={t.groomName} onChange={v => setTweak("groomName", v)} />
        <TweakText label="Vai (chú rể)" value={t.groomRole} onChange={v => setTweak("groomRole", v)} />
        <TweakText label="Tên thánh cô dâu" value={t.brideSaint} onChange={v => setTweak("brideSaint", v)} />
        <TweakText label="Họ tên cô dâu" value={t.brideName} onChange={v => setTweak("brideName", v)} />
        <TweakText label="Vai (cô dâu)" value={t.brideRole} onChange={v => setTweak("brideRole", v)} />
      </TweakSection>
      <TweakSection title="Nhà Trai">
        <TweakText label="Cha" value={t.groomFather} onChange={v => setTweak("groomFather", v)} />
        <TweakText label="Mẹ" value={t.groomMother} onChange={v => setTweak("groomMother", v)} />
        <TweakText label="Địa chỉ" value={t.groomAddress} onChange={v => setTweak("groomAddress", v)} />
      </TweakSection>
      <TweakSection title="Nhà Gái">
        <TweakText label="Cha" value={t.brideFather} onChange={v => setTweak("brideFather", v)} />
        <TweakText label="Mẹ" value={t.brideMother} onChange={v => setTweak("brideMother", v)} />
        <TweakText label="Địa chỉ" value={t.brideAddress} onChange={v => setTweak("brideAddress", v)} />
      </TweakSection>
      <TweakSection title="Hôn Lễ">
        <TweakText label="Địa điểm" value={t.ceremonyPlace} onChange={v => setTweak("ceremonyPlace", v)} />
        <TweakText label="Giờ" value={t.ceremonyTime} onChange={v => setTweak("ceremonyTime", v)} />
        <TweakText label="Thứ" value={t.ceremonyWeekday} onChange={v => setTweak("ceremonyWeekday", v)} />
        <TweakText label="Ngày" value={t.ceremonyDate} onChange={v => setTweak("ceremonyDate", v)} />
        <TweakText label="Âm lịch" value={t.lunar} onChange={v => setTweak("lunar", v)} />
      </TweakSection>
      <TweakSection title="Tiệc Cưới">
        <TweakText label="Người nhận" value={t.receiverName} onChange={v => setTweak("receiverName", v)} />
        <TweakText label="Nhà hàng" value={t.receptionVenue} onChange={v => setTweak("receptionVenue", v)} />
        <TweakText label="Địa chỉ" value={t.receptionAddress} onChange={v => setTweak("receptionAddress", v)} />
        <TweakText label="Thứ" value={t.receptionWeekday} onChange={v => setTweak("receptionWeekday", v)} />
        <TweakText label="Giờ" value={t.receptionTime} onChange={v => setTweak("receptionTime", v)} />
        <TweakText label="Ngày" value={t.receptionDate} onChange={v => setTweak("receptionDate", v)} />
        <TweakText label="Đón khách" value={t.welcomeTime} onChange={v => setTweak("welcomeTime", v)} />
        <TweakText label="Khai tiệc" value={t.feastTime} onChange={v => setTweak("feastTime", v)} />
      </TweakSection>
      <TweakSection title="Màu Sắc">
        <TweakRadio label="Sắc hoa" value={t.accent}
          options={[
            {label: "Hồng", value: "sage"},
            {label: "Tím", value: "lilac"},
            {label: "Cam", value: "poppy"},
          ]}
          onChange={v => setTweak("accent", v)} />
      </TweakSection>
    </TweaksPanel>
  );
}

// ---------- App ----------
function App() {
  const [t, setTweak] = useTweaks(G_DEFAULTS);
  const [stage, setStage] = useState("letter");
  const [receiver, setReceiver] = useState(t.receiverName);
  const [guestLoading, setGuestLoading] = useState(() => !!new URLSearchParams(window.location.search).get("to"));
  useEffect(() => { setReceiver(t.receiverName); }, [t.receiverName]);
  useEffect(() => {
    const id = new URLSearchParams(window.location.search).get("to");
    if (!id) return;
    resolveGuestName(id)
      .then(name => { if (name) setReceiver(name); })
      .catch(() => {})
      .finally(() => setGuestLoading(false));
  }, []);
  useReveal(stage === "main");

  useEffect(() => {
    const map = { sage: "#cf99a0", lilac: "#b09bd0", poppy: "#e08767" };
    const c = map[t.accent] || map.sage;
    document.documentElement.style.setProperty("--blush", c);
  }, [t.accent]);

  const open = () => { setStage("opening"); setTimeout(() => { setStage("main"); window.scrollTo({top:0}); }, 800); };
  const reset = () => { setStage("letter"); window.scrollTo({top:0, behavior:"smooth"}); };

  return (
    <>
      {(stage === "letter" || stage === "opening") && (
        <Letter t={t} receiver={receiver} guestLoading={guestLoading} onOpen={open} opening={stage === "opening"} />
      )}
      {stage === "main" && (
        <div className="stage-main">
          <Section1Hero t={t} />
          <Section2Reception t={t} receiver={receiver} guestLoading={guestLoading} />
          <Section3Timeline />
          <Section4Story />
          <SectionGallery />
          <Section5Rsvp receiver={receiver} />
          <footer>
            <div style={{color:"var(--sage-deep)", marginBottom: 10}}><Wreath size={58} /></div>
            <div className="fnames">{t.groomShort} &amp; {t.brideShort}</div>
            <div className="fmeta">{t.receptionDate.replace(/^Ngày\s*/i, "")} · TP. Hồ Chí Minh</div>
            <div style={{marginTop: 22}}>
              <button className="btn btn-ghost" onClick={reset}>Đóng thiệp</button>
            </div>
          </footer>
        </div>
      )}
      <GardenTweaks t={t} setTweak={setTweak} />
    </>
  );
}

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