// Apple Wallet pass section — preview + email-capture + signed-pass hook.
// Backend signing endpoint goes here. When deployed, set WALLET_ENDPOINT
// to your signing URL (see desert/wallet-server.example.js for sample code).
const WALLET_ENDPOINT = '/api/wallet-pass';

// Generate a vCard download as an immediate alternative to Apple Wallet
function downloadVCard(name) {
  const vcard = [
    'BEGIN:VCARD',
    'VERSION:3.0',
    'FN:Harlee Showalter',
    'ORG:Harlee Showalter at Desert Lounge',
    'TEL;TYPE=WORK:+18333521692',
    'EMAIL:harleepoglajen@gmail.com',
    'ADR;TYPE=WORK:;;75 N 100 E;St. George;UT;84770;US',
    'URL:https://harleeshowalter.com',
    'NOTE:Your stylist — Wed & Fri 9a-5p. ' + (name ? name + ' — ' : '') + 'Founding member.',
    'END:VCARD',
  ].join('\n');
  const blob = new Blob([vcard], { type: 'text/vcard' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'Harlee-Showalter.vcf';
  a.click();
  URL.revokeObjectURL(url);
}

const { useState: walletUS } = React;

function Wallet({ C, FF, HS, padY }) {
  return (
    <section id="wallet" className="m-section m-section-y" style={{
      padding: `${padY}px 56px`,
      background: `linear-gradient(180deg, ${C.cream} 0%, ${C.sand} 100%)`,
      position: 'relative', overflow: 'hidden',
    }}>
      {/* Decorative sun */}
      <div style={{
        position: 'absolute', top: -200, right: -200, width: 500, height: 500,
        borderRadius: '50%', background: `radial-gradient(circle, ${C.sun}77 0%, transparent 60%)`,
        pointerEvents: 'none',
      }} />

      <div className="m-grid-stack" style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 80, alignItems: 'center',
        position: 'relative', maxWidth: 1280, margin: '0 auto',
      }}>
        {/* LEFT — copy */}
        <div>
          <div className="m-eyebrow" style={{
            fontFamily: FF.mono, fontSize: 11, letterSpacing: '0.24em',
            textTransform: 'uppercase', color: C.rust, marginBottom: 24,
          }}>
            ✦ &nbsp; Apple Wallet &nbsp; ✦
          </div>
          <h2 className="m-h2" style={{
            fontFamily: FF.display, fontWeight: 300, fontStyle: 'italic',
            fontSize: 80 * HS, lineHeight: 0.95, margin: 0, letterSpacing: '-0.03em',
          }}>
            A chair that<br/>
            <span style={{ fontWeight: 600, fontStyle: 'normal', color: C.terra }}>
              lives in your pocket.
            </span>
          </h2>
          <p className="m-display-md" style={{
            fontFamily: FF.display, fontSize: 21, lineHeight: 1.5,
            marginTop: 28, maxWidth: 480, color: C.ink + 'cc',
          }}>
            Save Harlee&rsquo;s contact card to Apple Wallet — tap-to-call, directions to the studio, Instagram, and one-tap booking, all from your lock screen.
          </p>

          {/* Perks list */}
          <ul style={{
            listStyle: 'none', padding: 0, margin: '40px 0 0',
            display: 'grid', gap: 18,
          }}>
            {[
              ['One-tap directions', 'Opens Apple Maps with turn-by-turn to Desert Lounge.'],
              ['Call, text, or DM', 'Phone, Instagram, and booking links on the back of the pass.'],
              ['Surfaces when you&rsquo;re close', 'iPhone shows the pass on your lock screen near the studio.'],
              ['Refer a friend, both win', '$25 toward your next color when they book.'],
            ].map(([title, sub], i) => (
              <li key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 16 }}>
                <span style={{
                  flexShrink: 0, width: 28, height: 28, borderRadius: '50%',
                  background: C.terra, color: C.cream,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: FF.mono, fontSize: 11, fontWeight: 600,
                  marginTop: 2,
                }}>{String(i + 1).padStart(2, '0')}</span>
                <div>
                  <div style={{
                    fontFamily: FF.display, fontSize: 19, fontStyle: 'italic',
                    fontWeight: 500, lineHeight: 1.2,
                  }}>{title}</div>
                  <div style={{
                    fontFamily: FF.display, fontSize: 15, color: C.ink + 'aa',
                    lineHeight: 1.45, marginTop: 4,
                  }}>{sub}</div>
                </div>
              </li>
            ))}
          </ul>

          <a
            href="/Harlee.pkpass"
            data-c=""
            className="m-btn"
            style={{
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10,
              marginTop: 40, padding: '18px 32px', borderRadius: 999,
              background: C.ink, color: C.cream, textDecoration: 'none',
              fontFamily: 'Inter', fontSize: 14, fontWeight: 500, letterSpacing: '0.04em',
              boxShadow: `0 16px 40px -12px ${C.ink}aa`,
              transition: 'transform .25s',
            }}
            onMouseEnter={(e) => e.currentTarget.style.transform = 'translateY(-2px)'}
            onMouseLeave={(e) => e.currentTarget.style.transform = 'translateY(0)'}
          >
            <AppleWalletGlyph color={C.cream} />
            Add to Apple Wallet
          </a>
        </div>

        {/* RIGHT — pass preview */}
        <div style={{ display: 'flex', justifyContent: 'center', position: 'relative' }}>
          <PassPreview C={C} FF={FF} />
        </div>
      </div>
    </section>
  );
}

// ── PASS PREVIEW ──
function PassPreview({ C, FF }) {
  const [flipped, setFlipped] = walletUS(false);
  return (
    <div className="m-pass" style={{
      width: 340, position: 'relative',
    }}>
      {/* Flip toggle */}
      <button
        type="button"
        onClick={() => setFlipped(f => !f)}
        aria-label={flipped ? 'Show front of pass' : 'Show back of pass'}
        style={{
          position: 'absolute', top: -36, right: 4, zIndex: 5,
          background: 'transparent', border: `1px solid ${C.terra}55`,
          borderRadius: 999, padding: '6px 12px',
          fontFamily: FF.mono, fontSize: 9, letterSpacing: '0.22em',
          textTransform: 'uppercase', color: C.rust,
          cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6,
        }}
      >
        <span style={{ display: 'inline-block', transition: 'transform .4s', transform: flipped ? 'rotate(180deg)' : 'none' }}>↻</span>
        {flipped ? 'Front' : 'Back · ⓘ'}
      </button>

      <div style={{
        position: 'relative',
        transition: 'transform .5s cubic-bezier(.7,.05,.3,1)',
        transform: `rotateZ(-2deg) ${flipped ? 'rotateY(8deg)' : 'rotateY(-8deg)'}`,
        filter: 'drop-shadow(0 30px 60px rgba(58,40,32,0.25))',
      }}>
        {flipped
          ? <PassBack C={C} FF={FF} />
          : <PassFront C={C} FF={FF} />
        }
      </div>
    </div>
  );
}

function PassFront({ C, FF }) {
  return (
    <div style={{
      position: 'relative',
    }}>
      {/* The pass */}
      <div style={{
        background: C.cream,
        borderRadius: 18,
        overflow: 'hidden',
        border: `1px solid ${C.terra}33`,
        position: 'relative',
      }}>
        {/* Header strip — terra */}
        <div style={{
          background: C.terra, color: C.cream,
          padding: '16px 20px',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <div style={{
            fontFamily: FF.display, fontStyle: 'italic', fontSize: 22, fontWeight: 500,
            letterSpacing: '-0.01em',
          }}>
            Harlee.
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{
              fontFamily: FF.mono, fontSize: 8, letterSpacing: '0.2em',
              textTransform: 'uppercase', opacity: 0.85,
            }}>Member</div>
            <div style={{ fontFamily: FF.mono, fontSize: 12, fontWeight: 500, marginTop: 2 }}>
              N° 0142
            </div>
          </div>
        </div>

        {/* Hero image area */}
        <div style={{
          height: 130, position: 'relative', overflow: 'hidden',
          background: `linear-gradient(135deg, ${C.sun} 0%, ${C.terra}88 100%)`,
        }}>
          {/* Subtle sun rays */}
          <svg width="100%" height="100%" style={{ position: 'absolute', inset: 0 }}>
            <defs>
              <radialGradient id="pass-sun" cx="50%" cy="120%">
                <stop offset="0%" stopColor={C.sun} stopOpacity="1" />
                <stop offset="100%" stopColor={C.sun} stopOpacity="0" />
              </radialGradient>
            </defs>
            <circle cx="50%" cy="120%" r="120" fill="url(#pass-sun)" />
          </svg>
          {/* Saguaro silhouette */}
          <svg width="60" height="80" viewBox="0 0 60 80" style={{
            position: 'absolute', bottom: 0, right: 24, opacity: 0.4,
          }}>
            <rect x="24" y="14" width="12" height="66" rx="6" fill={C.ink} />
            <rect x="42" y="28" width="9" height="35" rx="4.5" fill={C.ink} />
            <rect x="32" y="34" width="20" height="7" rx="3.5" fill={C.ink} />
            <rect x="9" y="38" width="8" height="25" rx="4" fill={C.ink} />
            <rect x="13" y="42" width="17" height="6" rx="3" fill={C.ink} />
          </svg>
          <div style={{
            position: 'absolute', top: 12, left: 20,
            fontFamily: FF.script, fontSize: 28, color: C.cream,
            textShadow: '0 2px 8px rgba(0,0,0,0.15)', lineHeight: 1,
          }}>
            desert lounge
          </div>
        </div>

        {/* Primary field */}
        <div style={{ padding: '20px 20px 16px' }}>
          <div style={{
            fontFamily: FF.mono, fontSize: 9, letterSpacing: '0.22em',
            textTransform: 'uppercase', color: C.rust,
          }}>Member</div>
          <div style={{
            fontFamily: FF.display, fontStyle: 'italic', fontSize: 28,
            fontWeight: 500, lineHeight: 1, marginTop: 4, color: C.ink,
          }}>
            <span data-pass-name="">Your name</span>
          </div>
        </div>

        {/* Secondary fields */}
        <div style={{
          padding: '0 20px 16px',
          display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12,
        }}>
          <div>
            <div style={{
              fontFamily: FF.mono, fontSize: 8, letterSpacing: '0.22em',
              textTransform: 'uppercase', color: C.rust,
            }}>Member since</div>
            <div style={{
              fontFamily: FF.display, fontSize: 16, fontWeight: 500, marginTop: 4,
            }}>2026</div>
          </div>
          <div>
            <div style={{
              fontFamily: FF.mono, fontSize: 8, letterSpacing: '0.22em',
              textTransform: 'uppercase', color: C.rust,
            }}>Studio</div>
            <div style={{
              fontFamily: FF.display, fontSize: 16, fontWeight: 500, marginTop: 4,
              fontStyle: 'italic',
            }}>St. George, UT</div>
          </div>
        </div>

        {/* Auxiliary fields */}
        <div style={{
          padding: '0 20px 16px',
          display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12,
        }}>
          <div>
            <div style={{
              fontFamily: FF.mono, fontSize: 8, letterSpacing: '0.22em',
              textTransform: 'uppercase', color: C.rust,
            }}>Next visit</div>
            <div style={{ fontFamily: FF.display, fontSize: 14, fontWeight: 500, marginTop: 4 }}>
              When booked
            </div>
          </div>
          <div>
            <div style={{
              fontFamily: FF.mono, fontSize: 8, letterSpacing: '0.22em',
              textTransform: 'uppercase', color: C.rust,
            }}>Perks</div>
            <div style={{ fontFamily: FF.display, fontSize: 14, fontWeight: 500, marginTop: 4 }}>
              Active
            </div>
          </div>
        </div>

        {/* Barcode */}
        <div style={{
          margin: '0 20px 20px', padding: '14px',
          background: '#fff', borderRadius: 6,
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
        }}>
          <BarCode color={C.ink} />
          <div style={{
            fontFamily: 'ui-monospace, SF Mono, monospace',
            fontSize: 10, letterSpacing: '0.15em', color: C.ink + 'aa',
          }}>HS · 0142 · ST.GEORGE</div>
        </div>
      </div>

      {/* Punched circles on the sides like a real wallet pass */}
      <div style={{
        position: 'absolute', left: -8, top: '47%', width: 16, height: 16,
        borderRadius: '50%', background: C.sand,
      }} />
      <div style={{
        position: 'absolute', right: -8, top: '47%', width: 16, height: 16,
        borderRadius: '50%', background: C.sand,
      }} />
    </div>
  );
}

function PassBack({ C, FF }) {
  const fields = [
    {
      label: 'Directions',
      value: 'Open in Apple Maps →',
      href: 'https://maps.apple.com/?daddr=Harlee+Moore+Salon,+St+George+UT&dirflg=d',
      kind: 'maps',
    },
    {
      label: 'Address',
      value: 'Harlee Moore Salon\n123 Main St, Suite A\nSt. George, UT 84770',
    },
    {
      label: 'Book',
      value: 'Text Harlee →',
      href: 'sms:+14355550100',
    },
    {
      label: 'Hours',
      value: 'Tue–Sat · 10a – 6p\nClosed Sun & Mon',
    },
    {
      label: 'Cancellation',
      value: 'Please give 24 hrs notice for any changes. A 50% fee applies to no-shows.',
    },
    {
      label: 'Referrals',
      value: 'Send a friend, get $25 off your next visit. They get $25 off too.',
    },
  ];

  return (
    <div style={{
      position: 'relative',
    }}>
      <div style={{
        background: C.cream,
        borderRadius: 18,
        overflow: 'hidden',
        border: `1px solid ${C.terra}33`,
        position: 'relative',
        height: '100%',
        display: 'flex', flexDirection: 'column',
      }}>
        {/* Mini header bar */}
        <div style={{
          background: C.terra, color: C.cream,
          padding: '12px 18px',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          fontFamily: FF.mono, fontSize: 9, letterSpacing: '0.22em', textTransform: 'uppercase',
        }}>
          <span>Pass details</span>
          <span style={{ opacity: 0.8 }}>N° 0142</span>
        </div>

        {/* Scrollable back fields */}
        <div style={{
          padding: '6px 18px 18px',
          overflowY: 'auto',
          flex: 1,
        }}>
          {fields.map((f, i) => (
            <div key={i} style={{
              padding: '14px 0',
              borderBottom: i < fields.length - 1 ? `1px solid ${C.terra}22` : 'none',
            }}>
              <div style={{
                fontFamily: FF.mono, fontSize: 8, letterSpacing: '0.22em',
                textTransform: 'uppercase', color: C.rust, marginBottom: 6,
              }}>{f.label}</div>
              {f.href ? (
                <a href={f.href}
                  target={f.kind === 'maps' ? undefined : undefined}
                  style={{
                    fontFamily: FF.display, fontSize: 14, color: C.terra,
                    textDecoration: 'none', display: 'inline-flex',
                    alignItems: 'center', gap: 6, fontWeight: 500,
                    whiteSpace: 'pre-line',
                  }}>
                  {f.kind === 'maps' && <MapPinGlyph color={C.terra} />}
                  {f.value}
                </a>
              ) : (
                <div style={{
                  fontFamily: FF.display, fontSize: 13, color: C.ink,
                  lineHeight: 1.5, whiteSpace: 'pre-line',
                }}>{f.value}</div>
              )}
            </div>
          ))}
        </div>
      </div>

      {/* Punched circles match the front */}
      <div style={{
        position: 'absolute', left: -8, top: '47%', width: 16, height: 16,
        borderRadius: '50%', background: C.sand,
      }} />
      <div style={{
        position: 'absolute', right: -8, top: '47%', width: 16, height: 16,
        borderRadius: '50%', background: C.sand,
      }} />
    </div>
  );
}

function MapPinGlyph({ color }) {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{ flexShrink: 0 }}>
      <path d="M12 2C7.6 2 4 5.6 4 10c0 5.5 8 12 8 12s8-6.5 8-12c0-4.4-3.6-8-8-8z"
        stroke={color} strokeWidth="1.8" fill="none" strokeLinejoin="round" />
      <circle cx="12" cy="10" r="3" fill={color} />
    </svg>
  );
}

function BarCode({ color }) {
  // Render a fake but plausible barcode pattern.
  const widths = [3, 1, 2, 1, 3, 2, 1, 3, 1, 2, 1, 3, 1, 2, 3, 1, 2, 1, 1, 3, 2, 1, 3, 1, 2, 1, 3, 2, 1, 1, 3, 2, 1, 3, 1, 2, 3, 1];
  let x = 0;
  return (
    <svg width="100%" height="44" viewBox="0 0 240 44" preserveAspectRatio="none">
      {widths.map((w, i) => {
        const rect = i % 2 === 0
          ? <rect key={i} x={x} y="0" width={w * 2} height="44" fill={color} />
          : null;
        x += w * 2;
        return rect;
      })}
    </svg>
  );
}

// ── FORM ──
function WalletForm({ C, FF }) {
  const [name, setName] = walletUS('');
  const [email, setEmail] = walletUS('');
  const [status, setStatus] = walletUS('idle'); // idle | loading | success | error | unconfigured

  const liveUpdate = (n) => {
    setName(n);
    document.querySelectorAll('[data-pass-name]').forEach(el => {
      el.textContent = n.trim() || 'Your name';
    });
  };

  const handle = async (e) => {
    e.preventDefault();
    if (!name.trim() || !email.trim()) return;

    if (!WALLET_ENDPOINT) {
      // Dev mode — endpoint not configured. Pop a friendly state.
      setStatus('unconfigured');
      return;
    }

    setStatus('loading');
    try {
      const res = await fetch(WALLET_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: name.trim(), email: email.trim() }),
      });
      if (!res.ok) throw new Error('Pass generation failed');
      const blob = await res.blob();
      // Trigger download — iOS Safari recognizes application/vnd.apple.pkpass
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `harlee-showalter-${name.trim().toLowerCase().replace(/\s+/g, '-')}.pkpass`;
      document.body.appendChild(a);
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
      setStatus('success');
    } catch (err) {
      console.error(err);
      setStatus('error');
    }
  };

  const inputStyle = {
    width: '100%', padding: '14px 18px', fontSize: 15,
    fontFamily: FF.display, fontStyle: 'italic',
    background: C.cream, border: `1px solid ${C.terra}55`, borderRadius: 12,
    color: C.ink, outline: 'none',
  };

  return (
    <form onSubmit={handle} style={{
      marginTop: 40, padding: 24, background: C.cream + 'cc',
      border: `1px solid ${C.terra}33`, borderRadius: 18,
      backdropFilter: 'blur(4px)',
    }}>
      <div style={{
        fontFamily: FF.mono, fontSize: 10, letterSpacing: '0.22em',
        textTransform: 'uppercase', color: C.rust, marginBottom: 14,
      }}>
        Personalize your pass
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}
           className="m-grid-stack">
        <input
          type="text"
          placeholder="First name"
          value={name}
          onChange={(e) => liveUpdate(e.target.value)}
          style={inputStyle}
          required
        />
        <input
          type="email"
          placeholder="Email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          style={inputStyle}
          required
        />
      </div>

      <button
        type="submit"
        disabled={status === 'loading'}
        className="m-btn"
        data-c=""
        style={{
          marginTop: 14, width: '100%', padding: '16px 24px',
          background: C.ink, color: C.cream, border: 'none', borderRadius: 999,
          fontSize: 14, letterSpacing: '0.04em', cursor: 'none',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
          fontFamily: 'Inter', fontWeight: 500,
          opacity: status === 'loading' ? 0.6 : 1,
          transition: 'all .2s',
        }}>
        <AppleWalletGlyph color={C.cream} />
        {status === 'loading' ? 'Generating pass…' : 'Add to Apple Wallet'}
      </button>

      {/* Feedback states */}
      {status === 'unconfigured' && (
        <div style={{
          marginTop: 14, padding: '12px 16px',
          background: C.sand, borderRadius: 10,
          fontFamily: FF.display, fontSize: 14, fontStyle: 'italic',
          color: C.rust, lineHeight: 1.5,
        }}>
          ✦ Pass signing is being set up. You&rsquo;ll receive your wallet pass by email within 24 hours of submitting.
        </div>
      )}
      {status === 'success' && (
        <div style={{
          marginTop: 14, padding: '12px 16px',
          background: C.sand, borderRadius: 10,
          fontFamily: FF.display, fontSize: 14, fontStyle: 'italic',
          color: C.terra, lineHeight: 1.5,
        }}>
          ✦ Pass downloaded — open it on your iPhone to add to Wallet.
        </div>
      )}
      {status === 'error' && (
        <div style={{
          marginTop: 14, padding: '12px 16px',
          background: C.sand, borderRadius: 10,
          fontFamily: FF.display, fontSize: 14, fontStyle: 'italic',
          color: C.rust, lineHeight: 1.5,
        }}>
          Something went wrong. Try again, or text the studio at <span style={{ fontWeight: 600 }}>(435) ___-____</span>.
        </div>
      )}

      <div style={{
        marginTop: 14, fontFamily: FF.mono, fontSize: 9,
        letterSpacing: '0.18em', textTransform: 'uppercase',
        color: C.ink + '88', textAlign: 'center',
      }}>
        Works with iPhone · Apple Watch · Android (Google Wallet, soon)
      </div>
    </form>
  );
}

function AppleWalletGlyph({ color = '#fff' }) {
  // Stylized wallet pass glyph
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
      <rect x="3" y="6" width="18" height="13" rx="2.5" stroke={color} strokeWidth="1.6" />
      <path d="M3 10h18" stroke={color} strokeWidth="1.6" />
      <circle cx="17" cy="14.5" r="1.4" fill={color} />
    </svg>
  );
}

window.Wallet = Wallet;
