// ═══════════════════════════════════════════════════════════════════════
// Dyra Mobile — Home page blocks (mirrors desktop sections)
//   • MTestimonialsCarousel  — rotating reviews (matches desktop)
//   • MContactForm           — message form, posts to DyraStore.inquiries
// Loaded after m-shared.jsx, before m-screens-1.jsx.
// ═══════════════════════════════════════════════════════════════════════

(function () {
  const PM = window.DYRA_MOBILE_PALETTE;
  const TM = window.DYRA_MOBILE_TYPE;

  // ────────────────────────────────────────────────────────────────────
  // TESTIMONIALS CAROUSEL — same review data as the desktop home,
  // but laid out as a single full-width portrait card with an attribution
  // line + dots + arrows. Auto-advance every 7s; pause on touch.
  // ────────────────────────────────────────────────────────────────────
  const REVIEWS = [
    {
      stars: 5, heb: 'מדהים',
      headline: 'The kitchen was actually kosher — not just labeled.',
      body: 'Two sinks, two dishwashers, separated meat and milk down to the dish towels. We brought our 9-year-old who keeps strict — for the first time on a trip, she ate everything. The Shabbos lamps were already set. We did nothing.',
      stay: 'The 770 · 4 nights · Parshas Mishpatim',
      name: 'Chana M.', location: 'Lakewood, NJ',
    },
    {
      stars: 5, heb: 'מומלץ מאוד',
      headline: 'Showed up with three kids and a stroller. They had a Pack-n-Play already up.',
      body: 'My in-laws came in from Eretz Yisroel and we needed two beds in a kid-safe room. Dyra moved furniture. They messaged me at 11pm to confirm hot water. Who does that.',
      stay: 'Brooklyn Ave · 5 nights · family Yom Tov',
      name: 'Dovid K.', location: 'Toronto, Canada',
    },
    {
      stars: 5, heb: 'נקי וחם',
      headline: 'I have a wheelchair. They walked me through every threshold before I booked.',
      body: 'Other rentals say "accessible" and you arrive to four steps. Dyra sent measurements, photos of the bathroom doorway, even the slope of the ramp at 770. I cried a little when we got there. Everything fit.',
      stay: 'Empire Suite · 3 nights',
      name: 'Miriam S.', location: 'Manchester, UK',
    },
    {
      stars: 5, heb: 'בעזרת השם',
      headline: 'Booked a sheva brachos for 22 people on 6 days notice.',
      body: 'They flipped the dining room into a long table, set up a side room for the kallah, sourced a hot box. The bochurim slept four to a room — clean linens stacked in every closet. Best decision of the week.',
      stay: 'President Pl · 2 nights',
      name: 'Mendy B.', location: 'Crown Heights local',
    },
    {
      stars: 5, heb: 'מצוין',
      headline: 'Came in for Gimmel Tammuz. Felt like a home, not a hotel.',
      body: "Walked to the Ohel in fifteen minutes. Came back to a quiet apartment that smelled like cholent — they'd sent over a tray from the bakery. I will only stay with them now.",
      stay: 'Kingston House · 3 nights',
      name: 'Yossi R.', location: 'Melbourne, Australia',
    },
    {
      stars: 5, heb: 'שבת קודש',
      headline: 'Friday afternoon panic — they answered on the second ring.',
      body: "I forgot a hairdryer was muktza-controlled and couldn't figure out the switches. Their on-call rebbetzin walked me through it before licht bentchen. Real people, real understanding.",
      stay: 'Crown Studio · 2 nights',
      name: 'Rivka T.', location: 'Miami, FL',
    },
  ];

  function MStar({ filled }) {
    return (
      <svg width="13" height="13" viewBox="0 0 24 24" fill={filled ? PM.accent : 'none'} stroke={PM.accent} strokeWidth="1.5">
        <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" strokeLinejoin="round"/>
      </svg>
    );
  }

  function MTestimonialsCarousel() {
    const [idx, setIdx] = React.useState(0);
    const [paused, setPaused] = React.useState(false);

    React.useEffect(() => {
      if (paused) return;
      const t = setInterval(() => setIdx(i => (i + 1) % REVIEWS.length), 7000);
      return () => clearInterval(t);
    }, [paused]);

    const r = REVIEWS[idx];
    const goto = (i) => setIdx(((i % REVIEWS.length) + REVIEWS.length) % REVIEWS.length);

    return (
      <div
        onTouchStart={() => setPaused(true)}
        onTouchEnd={() => setPaused(false)}
        style={{
          background: PM.card,
          border: `0.5px solid ${PM.line}`,
          borderRadius: 16,
          padding: '22px 20px 18px',
          position: 'relative',
          overflow: 'hidden',
        }}
      >
        {/* Header — eyebrow + Hebrew accent (mirrors desktop card head) */}
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
          borderBottom: `0.5px solid ${PM.line}`, paddingBottom: 14, marginBottom: 18,
        }}>
          <div>
            <div style={{ fontSize: 9, letterSpacing: '0.24em', textTransform: 'uppercase', color: PM.muted, marginBottom: 2 }}>
              From our guests
            </div>
            <div style={{ fontFamily: TM.serif, fontSize: 18, color: PM.ink, lineHeight: 1.15 }}>
              What they said about staying with Dyra
            </div>
          </div>
          <div style={{ fontFamily: TM.hebrew, fontSize: 17, color: PM.accent, direction: 'rtl', flexShrink: 0, marginLeft: 12 }}>
            מן האורחים
          </div>
        </div>

        {/* Slide body — keyed for fade */}
        <div key={idx} style={{ animation: 'mTFade 500ms ease-out' }}>
          <div style={{ display: 'flex', gap: 4, alignItems: 'center', marginBottom: 12 }}>
            {Array.from({ length: 5 }).map((_, i) => <MStar key={i} filled={i < r.stars}/>)}
            <span style={{ marginLeft: 10, fontFamily: TM.hebrew, fontSize: 13, color: PM.accent, direction: 'rtl' }}>
              {r.heb}
            </span>
          </div>

          <div style={{
            fontFamily: TM.serif, fontSize: 22, lineHeight: 1.25,
            letterSpacing: '-0.005em', color: PM.ink, marginBottom: 14,
          }}>
            &ldquo;{r.headline}&rdquo;
          </div>

          <div style={{
            fontFamily: TM.sans, fontSize: 13, lineHeight: 1.6,
            color: PM.muted, marginBottom: 18,
          }}>
            {r.body}
          </div>

          <div style={{
            paddingTop: 14, borderTop: `0.5px solid ${PM.line}`,
          }}>
            <div style={{ fontSize: 9, letterSpacing: '0.18em', textTransform: 'uppercase', color: PM.muted, marginBottom: 6 }}>
              {r.stay}
            </div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, flexWrap: 'wrap' }}>
              <div style={{ fontFamily: TM.serif, fontSize: 17, color: PM.ink }}>— {r.name}</div>
              <div style={{ fontFamily: TM.sans, fontSize: 11, color: PM.muted }}>{r.location}</div>
            </div>
          </div>
        </div>

        {/* Controls — arrows + dots + tabular counter */}
        <div style={{
          marginTop: 18, paddingTop: 14,
          borderTop: `0.5px solid ${PM.line}`,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <div style={{
            fontFamily: TM.serif, fontSize: 13, color: PM.muted, fontVariantNumeric: 'tabular-nums',
            letterSpacing: '0.04em',
          }}>
            <span style={{ color: PM.ink }}>{String(idx + 1).padStart(2, '0')}</span>
            <span style={{ margin: '0 4px', color: PM.line }}>/</span>
            <span>{String(REVIEWS.length).padStart(2, '0')}</span>
          </div>

          <div style={{ display: 'flex', gap: 5 }}>
            {REVIEWS.map((_, i) => (
              <button
                key={i}
                onClick={() => setIdx(i)}
                aria-label={`Review ${i + 1}`}
                style={{
                  width: i === idx ? 18 : 6, height: 6, padding: 0, border: 'none',
                  borderRadius: 3, background: i === idx ? PM.accent : PM.line,
                  cursor: 'pointer', transition: 'all 240ms',
                }}
              />
            ))}
          </div>

          <div style={{ display: 'flex', gap: 8 }}>
            <button onClick={() => goto(idx - 1)} aria-label="Previous review" style={ctlBtn()}>‹</button>
            <button onClick={() => goto(idx + 1)} aria-label="Next review" style={ctlBtn()}>›</button>
          </div>
        </div>

        <style>{`
          @keyframes mTFade {
            from { opacity: 0; transform: translateY(4px); }
            to   { opacity: 1; transform: translateY(0); }
          }
        `}</style>
      </div>
    );
  }

  function ctlBtn() {
    return {
      width: 30, height: 30, padding: 0,
      background: 'transparent', border: `1px solid ${PM.line}`,
      borderRadius: 15, cursor: 'pointer', color: PM.ink,
      fontSize: 17, lineHeight: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
      WebkitTapHighlightColor: 'transparent',
    };
  }

  // ────────────────────────────────────────────────────────────────────
  // CONTACT FORM — mirrors D1ContactBlock from the desktop home.
  // Posts a new inquiry into DyraStore.inquiries on submit.
  // ────────────────────────────────────────────────────────────────────
  function MContactForm() {
    const [name, setName] = React.useState('');
    const [email, setEmail] = React.useState('');
    const [phone, setPhone] = React.useState('');
    const [message, setMessage] = React.useState('');
    const [sent, setSent] = React.useState(false);
    const [sending, setSending] = React.useState(false);
    const [error, setError] = React.useState(null);

    const fieldStyle = {
      width: '100%', boxSizing: 'border-box',
      padding: '12px 14px', border: `1px solid ${PM.line}`,
      borderRadius: 10, background: PM.bg, color: PM.ink,
      fontSize: 14, fontFamily: TM.sans, outline: 'none',
    };

    const submit = async () => {
      if (!name || !email || !message || sending) return;
      setSending(true);
      setError(null);
      try {
        const res = await fetch('/api/contact', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            guest_name: name,
            guest_email: email,
            guest_phone: phone || null,
            body: message,
          }),
        });
        if (!res.ok) {
          let detail = '';
          try { const j = await res.json(); detail = j && j.error ? ` (${j.error})` : ''; } catch (e) {}
          throw new Error('send-failed' + detail);
        }
        if (window.DyraStore && window.DyraStore.update) {
          try {
            window.DyraStore.update(s => {
              const id = window.DyraStore.uid('inq');
              s.inquiries.unshift({
                id, kind: 'contact', status: 'new',
                source: 'contact-form-mobile',
                receivedAt: new Date().toISOString().slice(0, 10),
                name, email, phone, notes: message,
              });
              s.notifications.unshift({
                id: window.DyraStore.uid('ntf'), at: new Date().toISOString(),
                kind: 'inquiry', read: false,
                title: `New contact · ${name}`,
                body: message.slice(0, 80),
                link: { screen: 'inquiries' },
              });
            });
          } catch (e) { /* ok */ }
        }
        setSent(true);
      } catch (err) {
        setError("Sorry — that didn't go through. Please try again, or WhatsApp 862-520-7797.");
      } finally {
        setSending(false);
      }
    };

    return (
      <div style={{
        background: PM.card,
        borderTop: `0.5px solid ${PM.line}`,
        borderBottom: `0.5px solid ${PM.line}`,
        padding: '36px 22px 40px',
      }}>
        <div style={{ textAlign: 'center', marginBottom: 22 }}>
          <div style={{
            fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase',
            color: PM.accent, marginBottom: 10,
          }}>Send a message</div>
          <div style={{
            fontFamily: TM.serif, fontSize: 26, lineHeight: 1.15, color: PM.ink,
            margin: '0 0 10px', letterSpacing: '-0.01em',
          }}>
            Have a question?<br/>We'll get back to you.
          </div>
          <div style={{ fontFamily: TM.sans, fontSize: 13, color: PM.muted, lineHeight: 1.6, textWrap: 'pretty' }}>
            Questions about kashrus, pricing, accessibility, or anything else —
            leave a note and we'll reply within a few hours.
          </div>
        </div>

        {sent ? (
          <div style={{
            background: PM.bg, border: `1px solid ${PM.line}`, borderRadius: 12,
            padding: '24px 20px', textAlign: 'center',
          }}>
            <div style={{ fontFamily: TM.serif, fontSize: 20, color: PM.ink, marginBottom: 8 }}>
              Thank you — message received.
            </div>
            <div style={{ fontFamily: TM.sans, fontSize: 13, color: PM.muted, lineHeight: 1.6 }}>
              We'll reply to <b style={{ color: PM.ink }}>{email}</b> within a few hours. For
              anything urgent, WhatsApp <a href="https://wa.me/18625207797" style={{ color: PM.accent, textDecoration: 'none' }}>862-520-7797</a>.
            </div>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <input placeholder="Your name" value={name} onChange={e => setName(e.target.value)} style={fieldStyle}/>
            <input placeholder="Email" type="email" value={email} onChange={e => setEmail(e.target.value)} style={fieldStyle}/>
            <input placeholder="Phone (optional)" value={phone} onChange={e => setPhone(e.target.value)} style={fieldStyle}/>
            <textarea placeholder="How can we help?" value={message} onChange={e => setMessage(e.target.value)} rows={4}
              style={{ ...fieldStyle, resize: 'vertical', minHeight: 96 }}/>
            <button
              onClick={submit}
              disabled={!name || !email || !message || sending}
              style={{
                marginTop: 8, height: 52, borderRadius: 26,
                background: PM.accent, color: '#fff', border: 'none',
                fontFamily: TM.sans, fontSize: 14, fontWeight: 500, letterSpacing: '0.06em',
                textTransform: 'uppercase',
                cursor: (!name || !email || !message) ? 'not-allowed' : (sending ? 'wait' : 'pointer'),
                opacity: (!name || !email || !message) ? 0.5 : (sending ? 0.7 : 1),
                WebkitTapHighlightColor: 'transparent',
              }}
            >
              {sending ? 'Sending…' : 'Send message'}
            </button>
            {error && (
              <div style={{ fontSize: 12, color: '#c0392b', marginTop: 4, textAlign: 'center', fontFamily: TM.sans }}>{error}</div>
            )}
          </div>
        )}
      </div>
    );
  }

  Object.assign(window, { MTestimonialsCarousel, MContactForm });
})();
