/* The Reco voucher card: exactly the landing page's minimal ticket, used everywhere (owner app, customer pages, landing mockups).
     tone    = the fill colour the business picked: 'green' | 'navy' | 'light' | 'cream'
     variant = 'muted' for a paused / already used voucher
   The small print (validity, one use per new customer, terms) is written under the card, outside it (VoucherNotes).
   VoucherBack is the other side of the card: the QR code, shown after the card flips over.
   Exports: VoucherTicket, VoucherNotes, VoucherBack, ticketDay, startWord, TICKET_TONES */

// Short date in Israel time, e.g. 15.11
const ticketDay = t => new Date(t).toLocaleDateString('he-IL', { day: 'numeric', month: 'numeric', timeZone: 'Asia/Jerusalem' });

// When a voucher that has not started yet opens: "מהבוקר" (later today), "ממחר", or a date. The exact hour is never shown.
const israelDay = t => new Date(t).toLocaleDateString('en-CA', { timeZone: 'Asia/Jerusalem' });
const startWord = startMs => {
  const d = israelDay(startMs), now = Date.now();
  if (d === israelDay(now)) return 'מהבוקר';
  if (d === israelDay(now + 864e5)) return 'ממחר';
  return `מ-${ticketDay(startMs)}`;
};

const ticketDays = d => d === 1 ? 'ליום אחד' : d === 2 ? 'ליומיים' : `ל-${d} ימים`;

const TICKET_TONES = {
  green: { label: 'ירוק',  bg: 'var(--reco-green)', fg: '#fff', sub: 'rgba(255,255,255,0.82)', chip: 'rgba(255,255,255,0.18)', chipFg: '#fff' },
  navy:  { label: 'כחול',  bg: 'var(--reco-navy)', fg: '#fff', sub: 'rgba(255,255,255,0.7)', chip: 'rgba(255,255,255,0.14)', chipFg: '#fff' },
  light: { label: 'לבן',   bg: '#fff', fg: 'var(--reco-navy)', sub: 'var(--iv-ink-soft)', chip: 'var(--iv-glow)', chipFg: 'var(--reco-green-deep)', border: '1.5px solid var(--iv-line-strong)' },
  cream: { label: 'קרם',   bg: 'var(--iv-paper-warmer)', fg: 'var(--reco-navy)', sub: 'var(--iv-ink-soft)', chip: '#fff', chipFg: 'var(--reco-green-deep)' },
  muted: { bg: '#fff', fg: 'var(--reco-navy)', sub: 'var(--iv-ink-soft)', chip: 'var(--iv-paper-warmer)', chipFg: 'var(--iv-ink-soft)', border: '1.5px solid var(--iv-line-strong)' },
};
const toneOf = (variant, tone) => TICKET_TONES[variant === 'muted' ? 'muted' : (tone || window.RECO_TONE || 'green')] || TICKET_TONES.green;

// The icon in the corner follows the kind of business, guessed from its name and the reward (no setting needed)
const ICON_PATHS = {
  gift: 'M20 12v8a1 1 0 01-1 1H5a1 1 0 01-1-1v-8M2 7h20v5H2zM12 22V7M12 7H7.5a2.5 2.5 0 010-5C11 2 12 7 12 7zM12 7h4.5a2.5 2.5 0 000-5C13 2 12 7 12 7z',
  coffee: 'M4 8h13v5a5 5 0 01-5 5H9a5 5 0 01-5-5V8zM17 9h2.5a2.5 2.5 0 010 5H17M7 2v2.5M11 2v2.5',
  bar: 'M5 3h14l-7 9-7-9zM12 12v9M8 21h8',
  spa: 'M11 20A7 7 0 019.8 6.1C15.5 5 17 4.48 19 2c1 2 2 4.18 2 8 0 5.5-4.78 10-10 10zM2 21c0-3 1.85-5.36 5.08-6C9.5 14.52 12 13 13 12',
  salon: 'M9 6a3 3 0 11-6 0 3 3 0 016 0zM9 18a3 3 0 11-6 0 3 3 0 016 0zM20 4L8.12 15.88M14.47 14.48L20 20M8.12 8.12L12 12',
  restaurant: 'M3 2v7c0 1.1.9 2 2 2h4a2 2 0 002-2V2M7 2v20M21 15V2a5 5 0 00-5 5v6c0 1.1.9 2 2 2h3zm0 0v7',
  gym: 'M6.5 6.5l11 11M21 21l-1-1M3 3l1 1M18 22l4-4M2 6l4-4M3 10l7-7M14 21l7-7',
  retail: 'M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4zM3 6h18M16 10a4 4 0 01-8 0',
};
const ICON_WORDS = [
  ['coffee', /קפה|אספרסו|קפוצ|מאפ|קונדיטור|בייגל|coffee|cafe|espresso|bakery/i],
  ['bar', /(^|\s)בר(\s|$)|קוקטייל|בירה|יין|פאב|bar|pub|cocktail|wine|beer/i],
  ['spa', /ספא|מסאז|עיסוי|פדיקור|מניקור|spa|massage|wellness/i],
  ['salon', /מספרה|תספורת|שיער|ציפורני|איפור|סלון|hair|barber|salon|nail|beauty/i],
  ['gym', /כושר|יוגה|פילאטיס|אימון|gym|fitness|yoga|pilates/i],
  ['restaurant', /מסעדה|ארוח|ערב|פיצה|פיצר|סושי|המבורגר|בורגר|שווארמה|פלאפל|גריל|מטבח|קינוח|גלידה|restaurant|pizza|sushi|burger|grill|kitchen|bistro/i],
  ['retail', /חנות|בוטיק|ביגוד|אופנה|store|shop|boutique/i],
];
const iconKind = (business, reward, label) => {
  const byLabel = label && ICON_WORDS.find(([, re]) => re.test(label));   // what the owner wrote wins
  const txt = `${business || ''} ${reward || ''}`;
  const hit = byLabel || ICON_WORDS.find(([, re]) => re.test(txt));
  return hit ? hit[0] : 'gift';
};
const KIND_LABEL = { coffee: 'בית קפה', bar: 'בר', spa: 'ספא', salon: 'מספרה', restaurant: 'מסעדה', gym: 'חדר כושר', retail: 'חנות' };
const GiftGlyph = ({ kind = 'gift' }) => (
  <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" style={{ opacity: 0.9 }} aria-hidden="true">
    <path d={ICON_PATHS[kind] || ICON_PATHS.gift}/>
  </svg>
);

// the little tag at the top: the Reco mark and the product name (or a plain word for the owner's cards)
function TicketChip({ c, brand, text, label }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, height: 26, padding: brand ? '0 11px 0 9px' : '0 11px', borderRadius: 99, background: c.chip, color: c.chipFg,
                   fontSize: 11.5, fontWeight: 600, fontFamily: 'var(--iv-font-mono)', letterSpacing: '0.08em' }}>
      {brand && (
        <span style={{ width: 18, height: 18, borderRadius: 99, background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <img src="/assets/reco-mark.png" alt="" style={{ width: 12, height: 'auto', display: 'block' }} />
        </span>
      )}
      {brand ? (label || 'Reco - שובר המלצה') : text}
    </span>
  );
}

const Perforation = ({ c }) => (
  <div style={{ position: 'relative', height: 0 }}>
    <span style={{ position: 'absolute', left: -9, top: -9, width: 18, height: 18, borderRadius: 99, background: 'var(--reco-page-bg, #F6FAF8)' }} />
    <span style={{ position: 'absolute', right: -9, top: -9, width: 18, height: 18, borderRadius: 99, background: 'var(--reco-page-bg, #F6FAF8)' }} />
    <div style={{ position: 'absolute', left: 16, right: 16, top: 0, borderTop: `1.5px dashed ${c.fg}`, opacity: 0.28 }} />
  </div>
);

const PinIcon = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" style={{ flexShrink: 0 }}>
    <path d="M12 21s7-6.2 7-11a7 7 0 10-14 0c0 4.8 7 11 7 11z"/><circle cx="12" cy="10" r="2.5"/>
  </svg>
);

// The small print: one line of asterisk notes inside the card
function VoucherNotes({ days = 3, startsAt, endsAt, immediate = false, terms, color, style = {} }) {
  let when = immediate ? 'מיום ההנפקה' : 'החל ממחרת ההנפקה';
  if (startsAt && endsAt) {
    const startMs = new Date(startsAt).getTime();
    when = startMs > Date.now() ? `החל ${startWord(startMs)}` : `עד ${ticketDay(new Date(endsAt).getTime() - 60000)}`;
  }
  const parts = [`תקף ${ticketDays(days)}, ${when}`, 'ללקוח/ה חדש/ה בלבד'];
  if (terms) parts.push(terms);
  return (
    <div style={{ padding: '0 22px 15px', fontSize: 10.5, lineHeight: 1.45, color, opacity: 0.85, textAlign: 'start', ...style }}>
      * {parts.join(' · ')}
    </div>
  );
}

function VoucherTicket({ reward, business, days = 3, startsAt, endsAt, terms, from, immediate = false, place, redeemed, hideDetails = false, notes = !window.RECO_NO_NOTES,
                         tone, icon, label = window.RECO_LABEL, variant = 'filled', tag = 'פעיל', onClick, preview, style = {} }) {
  const c = toneOf(variant, tone);
  const interactive = onClick ? {
    role: 'button', tabIndex: 0, 'aria-label': 'עריכת השובר', onClick,
    onKeyDown: e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onClick(); } },
  } : {};
  const showNotes = notes && !hideDetails && !redeemed;

  const card = (
    <div className={`reco-vt${onClick ? ' clickable' : ''}`} {...interactive} style={{
      position: 'relative', width: '100%', borderRadius: 20, textAlign: 'start',
      background: c.bg, color: c.fg, border: c.border || 'none', boxShadow: preview ? 'var(--iv-shadow-2)' : '0 18px 44px rgba(16,36,63,0.16)',
    }}>
      <div style={{ padding: '20px 22px 18px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 22 }}>
          {redeemed
            ? <TicketChip c={c} text={`מומש${redeemed.at ? ` · ${ticketDay(redeemed.at)}` : ''}`} />
            : <TicketChip c={c} brand={from != null} text={tag} label={(label && label.trim()) || KIND_LABEL[icon || iconKind(business, reward)]} />}
          {!redeemed && <GiftGlyph kind={icon || iconKind(business, reward, label)} />}
        </div>
        <div className="reco-vt-reward" style={{ fontFamily: 'var(--iv-font-sans)', fontWeight: 700, fontSize: 26, lineHeight: 1.08, letterSpacing: '-0.025em', textWrap: 'balance',
                                                 ...(hideDetails ? { padding: '10px 0 22px' } : {}),
                                                 ...(redeemed ? { textDecoration: 'line-through', textDecorationThickness: 2, color: 'var(--iv-ink-soft)' } : {}) }}>
          {hideDetails ? business : reward}
        </div>
        {showNotes && <VoucherNotes days={days} startsAt={startsAt} endsAt={endsAt} immediate={immediate} terms={terms} color={c.sub} style={{ padding: 0, marginTop: 14 }} />}
      </div>

      <Perforation c={c} />

      <div style={{ padding: '13px 22px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
        {(() => {
          const pin = place && place.href;
          const link = pin && !onClick && !preview;   // in the owner app the whole card opens the editor, so the pin is only a mark
          const Tag = link ? 'a' : 'span';
          return (
            <Tag {...(link ? { href: place.href, target: '_blank', rel: 'noopener', 'aria-label': `${business} בגוגל מפות`, onClick: e => e.stopPropagation() } : {})}
                 style={{ display: 'inline-flex', alignItems: 'center', gap: 6, minWidth: 0, fontSize: 12.5, fontWeight: 500, color: c.sub, textDecoration: 'none' }}>
              {pin && <PinIcon />}
              <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{business}</span>
            </Tag>
          );
        })()}
        <span style={{ flexShrink: 0, fontFamily: 'var(--iv-font-mono)', fontSize: 11.5, color: c.sub, letterSpacing: '0.1em' }}>
          {redeemed && from ? `מתנה מ${from}` : 'שימוש אחד'}
        </span>
      </div>
    </div>
  );

  return <div style={{ width: '100%', maxWidth: 440, margin: '0 auto', ...style }}>{card}</div>;
}

// The back of the card: the same fill, with the QR code in the middle
function VoucherBack({ tone, qr, codeText, business, reward, icon, label = window.RECO_LABEL, style = {} }) {
  const c = toneOf('filled', tone);
  return (
    <div style={{ position: 'relative', width: '100%', borderRadius: 20, background: c.bg, color: c.fg, border: c.border || 'none', boxShadow: '0 18px 44px rgba(16,36,63,0.16)', textAlign: 'center', ...style }}>
      <div style={{ padding: '20px 22px 22px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
          <TicketChip c={c} brand label={(label && label.trim()) || KIND_LABEL[icon || iconKind(business, reward, label)]} />
          <GiftGlyph kind={icon || iconKind(business, reward, label)} />
        </div>
        <div style={{ width: 196, maxWidth: '100%', margin: '0 auto', padding: 12, background: '#fff', borderRadius: 18, boxSizing: 'border-box' }}>{qr}</div>
      </div>
      <Perforation c={c} />
      <div style={{ padding: '13px 22px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
        <span style={{ fontSize: 12.5, fontWeight: 500, color: c.sub }}>{business}</span>
        <span dir="ltr" style={{ fontFamily: 'var(--iv-font-mono)', fontSize: 12.5, fontWeight: 600, letterSpacing: '0.08em', color: c.fg }}>{codeText}</span>
      </div>
    </div>
  );
}

window.voucherKindLabel = (business, reward) => KIND_LABEL[iconKind(business, reward)] || '';
Object.assign(window, { VoucherTicket, VoucherNotes, VoucherBack, ticketDay, startWord, TICKET_TONES });
