// Delen, bewaren en "Ik ga hierheen!" voor gastenwebsites. Los blok: werkt met elk huis uit VH_DATA.
// Ook: window.vhTrack(event, props) als één plek voor analytics-events (nu: console + dataLayer; later Plausible).
(() => {
const NS = window.VakantiehuisplatformDesignSystem_2f09bb;
const { Button, Icon } = NS;

window.vhTrack = window.vhTrack || function (event, props) {
  try { (window.dataLayer = window.dataLayer || []).push({ event, ...(props || {}) }); if (window.plausible) window.plausible(event, { props }); } catch (e) {}
};
const SAVE_KEY = 'vh-saved';
const u = (k => (window.VH_I18N && window.VH_I18N.ui ? window.VH_I18N.ui(k) : k));
const loadSaved = () => { try { return JSON.parse(localStorage.getItem(SAVE_KEY) || '[]'); } catch (e) { return []; } };

function ShareBar({ house, label, onDark, style }) {
  const url = location.href.split('#')[0];
  const id = house.name;
  const [saved, setSaved] = React.useState(() => loadSaved().includes(id));
  const [open, setOpen] = React.useState(false);
  const [copied, setCopied] = React.useState(false);
  const text = (label || house.name) + ' in ' + house.place + ': ' + u('kijk eens!');
  const toggleSave = () => { const s = loadSaved(); const next = saved ? s.filter(x => x !== id) : [...s, id]; try { localStorage.setItem(SAVE_KEY, JSON.stringify(next)); } catch (e) {} setSaved(!saved); window.vhTrack(saved ? 'unsave' : 'save', { house: id }); };
  const share = async () => {
    window.vhTrack('share_open', { house: id });
    if (navigator.share) { try { await navigator.share({ title: house.name, text, url }); window.vhTrack('share_native', { house: id }); return; } catch (e) { if (e && e.name === 'AbortError') return; } }
    setOpen(o => !o);
  };
  const copy = () => { try { navigator.clipboard.writeText(url); } catch (e) {} setCopied(true); setTimeout(() => setCopied(false), 2000); window.vhTrack('share_copy', { house: id }); };
  const btn = { display: 'inline-flex', alignItems: 'center', gap: 8, minHeight: 44, padding: '0 14px', borderRadius: 'var(--radius-btn)', border: onDark ? '1px solid rgba(255,255,255,.5)' : '1.5px solid var(--border)', background: onDark ? 'rgba(14,14,12,.45)' : 'var(--surface-card)', color: onDark ? '#fff' : 'var(--text-1)', fontSize: 16, fontWeight: 600, cursor: 'pointer', backdropFilter: onDark ? 'blur(8px)' : undefined };
  const links = [['message-circle', 'WhatsApp', 'https://wa.me/?text=' + encodeURIComponent(text + ' ' + url)], ['mail', u('E-mail'), 'mailto:?subject=' + encodeURIComponent(house.name) + '&body=' + encodeURIComponent(text + '\n' + url)], ['facebook', 'Facebook', 'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(url)]];
  return <div style={{ position: 'relative', display: 'flex', gap: 8, flexWrap: 'wrap', ...style }}>
    <button onClick={toggleSave} aria-pressed={saved} style={btn}><Icon name="heart" size={18} style={saved ? { background: '#e0475b' } : null} />{saved ? u('Bewaard') : u('Bewaar')}</button>
    <button onClick={share} aria-expanded={open} style={btn}><Icon name="share-2" size={18} />{u('Deel')}</button>
    {open && <div role="menu" style={{ position: 'absolute', ...(onDark ? { bottom: 'calc(100% + 8px)' } : { top: 'calc(100% + 8px)' }), left: 0, zIndex: 30, minWidth: 220, padding: 8, background: 'var(--surface-card)', color: 'var(--text-1)', border: '1px solid var(--border)', borderRadius: 'var(--radius-md)', boxShadow: 'var(--shadow-card)' }}>
      {links.map(([ic, n, href]) => <a key={n} role="menuitem" href={href} target="_blank" rel="noopener" onClick={() => { window.vhTrack('share_' + n.toLowerCase(), { house: id }); setOpen(false); }} style={{ display: 'flex', alignItems: 'center', gap: 10, minHeight: 44, padding: '0 10px', color: 'inherit', textDecoration: 'none', borderRadius: 'var(--radius-sm)', fontSize: 16 }}><Icon name={ic} size={18} />{n}</a>)}
      <button role="menuitem" onClick={copy} style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', minHeight: 44, padding: '0 10px', background: 'none', border: 0, color: 'inherit', fontSize: 16, cursor: 'pointer' }}><Icon name={copied ? 'check' : 'link'} size={18} />{copied ? u('Link gekopieerd') : u('Kopieer link')}</button>
    </div>}
  </div>;
}

// Kaart na een boeking: "Hey! Ik zit binnenkort hier". Maakt ook een Instagram-story-afbeelding (1080x1920).
function TripShare({ house, dates, photo }) {
  const url = location.href.split('#')[0];
  const msg = u('Hey! Ik zit binnenkort hier') + ' 🏔️ ' + house.name + ', ' + house.place + ' (' + dates + ')';
  const [busy, setBusy] = React.useState(false);
  const [copiedCap, setCopiedCap] = React.useState(false);
  const [ok, setOk] = React.useState(false);
  const handle = window.vhS ? window.vhS('igHandle', '@trattenbach21') : '@trattenbach21';
  const tagH = '#' + house.name.toLowerCase().replace(/[^a-z0-9]/g, '');
  const caption = u('Ik zit binnenkort hier!') + ' 🏔️ ' + house.name + ', ' + house.place + ' ' + handle + ' ' + tagH;
  const copyCap = () => { try { navigator.clipboard.writeText(caption); } catch (e) {} setCopiedCap(true); setTimeout(() => setCopiedCap(false), 2000); window.vhTrack('trip_collab_copy', { house: house.name }); };
  const story = () => {
    setBusy(true); window.vhTrack('trip_story', { house: house.name });
    const img = new Image(); img.crossOrigin = 'anonymous';
    img.onload = () => {
      const c = document.createElement('canvas'); c.width = 1080; c.height = 1920; const g = c.getContext('2d');
      const s = Math.max(1080 / img.width, 1920 / img.height); const w = img.width * s, h = img.height * s;
      g.drawImage(img, (1080 - w) / 2, (1920 - h) / 2, w, h);
      const gr = g.createLinearGradient(0, 1000, 0, 1920); gr.addColorStop(0, 'rgba(0,0,0,0)'); gr.addColorStop(1, 'rgba(0,0,0,.75)'); g.fillStyle = gr; g.fillRect(0, 0, 1080, 1920);
      g.fillStyle = '#fff'; g.font = '600 64px system-ui, sans-serif'; g.fillText(u('Ik zit binnenkort hier!'), 80, 1560);
      g.font = '700 96px system-ui, sans-serif'; g.fillText(house.name, 80, 1680);
      g.font = '400 48px system-ui, sans-serif'; g.fillText(house.place + ' · ' + dates, 80, 1760);
      const a = document.createElement('a'); a.download = 'ik-ga-naar-' + house.name.toLowerCase().replace(/\s+/g, '-') + '.png'; a.href = c.toDataURL('image/png'); a.click(); setBusy(false);
    };
    img.onerror = () => setBusy(false);
    img.src = photo;
  };
  return <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr)', gap: 12, padding: 16, borderRadius: 'var(--radius-lg)', border: '1px solid var(--border)', background: 'var(--surface-alt)' }}>
    <div style={{ position: 'relative', borderRadius: 'var(--radius-md)', overflow: 'hidden', aspectRatio: '16/9', background: 'var(--surface-sunken)' }}>
      <img src={photo} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
      <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(0,0,0,0) 40%, rgba(0,0,0,.7))' }}></div>
      <div style={{ position: 'absolute', left: 16, bottom: 14, color: '#fff' }}><div style={{ fontSize: 15, fontWeight: 600 }}>{u('Ik zit binnenkort hier!')}</div><div style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 700, lineHeight: 1.1 }}>{house.name}</div><div style={{ fontSize: 14 }}>{house.place} · {dates}</div></div>
    </div>
    <strong style={{ fontSize: 17 }}>{u('Vertel het je vrienden')}</strong>
    <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
      <Button icon="instagram" onClick={story} disabled={busy}>{busy ? u('Even geduld…') : 'Instagram-story'}</Button>
      <Button variant="secondary" icon="message-circle" onClick={() => { window.vhTrack('trip_whatsapp', { house: house.name }); window.open('https://wa.me/?text=' + encodeURIComponent(msg + ' ' + url), '_blank', 'noopener'); }}>WhatsApp</Button>
      <Button variant="secondary" icon="facebook" onClick={() => { window.vhTrack('trip_facebook', { house: house.name }); window.open('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(url), '_blank', 'noopener'); }}>Facebook</Button>
    </div>
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: 14, borderRadius: 'var(--radius-md)', background: 'var(--surface-card)', border: '1px solid var(--border)' }}>
      <strong style={{ fontSize: 16 }}>{u('Samen posten met')} {handle}</strong>
      <span style={{ fontSize: 15, color: 'var(--text-2)' }}>{u('Dan staat je post ook op het Instagram-account van het huis.')}</span>
      <ol style={{ margin: 0, paddingLeft: 20, fontSize: 15, display: 'flex', flexDirection: 'column', gap: 4 }}>
        <li>{u('Kopieer de tekst hieronder en plaats je foto of de story-afbeelding op Instagram.')}</li>
        <li>{u('Tik op')} <strong>{u('Mensen taggen')}</strong> {u('en dan')} <strong>{u('Samenwerker uitnodigen')}</strong>. {u('Kies')} {handle}.</li>
        <li>{u('Het huis accepteert, en je post verschijnt op beide accounts.')}</li>
      </ol>
      <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}><code style={{ flex: '1 1 220px', minWidth: 0, padding: '8px 10px', borderRadius: 'var(--radius-sm)', background: 'var(--surface-alt)', fontSize: 14, overflowWrap: 'anywhere' }}>{caption}</code><Button size="sm" variant="secondary" icon={copiedCap ? 'check' : 'copy'} onClick={copyCap}>{copiedCap ? u('Gekopieerd') : u('Kopieer tekst')}</Button></div>
      <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 15, cursor: 'pointer' }}><input type="checkbox" checked={ok} onChange={e => { setOk(e.target.checked); if (e.target.checked) window.vhTrack('trip_repost_ok', { house: house.name }); }} style={{ width: 20, height: 20, accentColor: 'var(--accent)', flex: 'none' }} />{u('Het huis mag mijn vakantiefoto’s ook zelf delen, met mijn naam erbij.')}</label>
    </div>
    <span style={{ fontSize: 14, color: 'var(--text-2)' }}>{u('We delen geen namen of data zonder dat jij op een knop drukt.')}</span>
  </div>;
}
Object.assign(window, { VHShareBar: ShareBar, VHTripShare: TripShare });
})();
