/* Viamar — post-delivery customer survey (private feedback that GATES the
   public Google review).

   Flow: delivered shipment → "How did we do?" → star rating + quick tags +
   optional comment → submit to POST /app/survey. Then:
     • rating >= 4  → "Glad we delivered! Share it on Google?" → VIAMAR_REVIEW_URL
     • rating <  4  → "Thank you — your agent will follow up" → opens agent chat
   So happy customers are routed to Google and unhappy ones are caught privately.

   Published as window.ViamarSurvey = { open(opts), close() }. Self-mounting
   (mirrors app/chat-panel.jsx): open() appends its own host div and renders the
   modal; close() unmounts. opts = { ship?, source? }.
   Uses the shared tokens (T/FB/FD/FM, Icon) every shell loads via components.jsx. */
(function () {
  var host = null, root = null;

  var TAGS = ['Clear communication', 'On-time delivery', 'Careful handling', 'Fair price', 'Easy paperwork', 'Helpful agent'];

  function apiBase() {
    if (window.ViamarAPI && window.ViamarAPI.apiBase) return (window.ViamarAPI.apiBase() || '').replace(/\/+$/, '');
    return (window.VIAMAR_API_BASE || (window.localStorage && localStorage.getItem('viamar.api.base')) || '').replace(/\/+$/, '');
  }
  function sessionToken() {
    try { var s = window.ViamarAPI && window.ViamarAPI.session ? window.ViamarAPI.session() : null; return (s && s.session_token) || ''; }
    catch (e) { return ''; }
  }
  function reviewUrl() {
    return window.VIAMAR_REVIEW_URL || 'https://www.google.com/maps/search/?api=1&query=Viamar+Scilla+Transport+International+Vaughan';
  }
  function surveyQuoteId(ship) {
    if (!ship) return '';
    return ship.quote_id || ship.quoteId || ship.quote_ref || ship.quoteRef || ship.id || '';
  }

  function Stars(props) {
    var v = props.value || 0;
    return React.createElement('div', { style: { display: 'flex', gap: 8, justifyContent: 'center', margin: '6px 0 2px' } },
      [1, 2, 3, 4, 5].map(function (n) {
        var on = n <= v;
        return React.createElement('button', {
          key: n, onClick: function () { props.onPick(n); }, 'aria-label': n + ' star' + (n > 1 ? 's' : ''),
          style: { background: 'transparent', border: 0, cursor: 'pointer', padding: 4, lineHeight: 0 },
        }, React.createElement(window.Icon, { name: 'star', size: 38, color: on ? (T.gold || '#C8A24B') : (T.line || '#E5E8EC'), stroke: 2, fill: on ? (T.gold || '#C8A24B') : 'none' }));
      })
    );
  }

  function SurveyModal(props) {
    var ship = props.ship || null;
    var source = props.source || 'app';
    var st = React.useState(0), rating = st[0], setRating = st[1];
    var tg = React.useState([]), tags = tg[0], setTags = tg[1];
    var cm = React.useState(''), comment = cm[0], setComment = cm[1];
    var cn = React.useState(false), consent = cn[0], setConsent = cn[1];
    var ph = React.useState('form'), phase = ph[0], setPhase = ph[1]; // form | sending | thanks-high | thanks-low | error
    var ru = React.useState(null), review_url = ru[0], setReviewUrl = ru[1];
    var toggleTag = function (t) { setTags(function (arr) { return arr.indexOf(t) >= 0 ? arr.filter(function (x) { return x !== t; }) : arr.concat([t]); }); };

    var submit = function () {
      if (!rating) return;
      setPhase('sending');
      if (window.ViamarAnalytics) window.ViamarAnalytics.track('survey_submit_attempted', { source: source });
      var base = apiBase();
      var body = {
        session_token: sessionToken() || undefined,
        quote_ref: surveyQuoteId(ship) || undefined,
        email: (ship && ship.email) || undefined,
        rating: rating, tags: tags, comment: comment.trim() || undefined,
        testimonial_consent: consent, source: source,
      };
      fetch(base + '/app/survey', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
        .then(function (res) {
          return res.json().catch(function () { return {}; }).then(function (json) {
            if (!res.ok) throw new Error(json.error || 'Feedback could not be saved.');
            return json;
          });
        })
        .then(function (json) {
          setReviewUrl((json && json.review_url) || null);
          setPhase((json && json.review_prompted) ? 'thanks-high' : 'thanks-low');
        })
        .catch(function () { setPhase('error'); });
    };

    var recordReviewClick = function () {
      if (window.ViamarAnalytics) ViamarAnalytics.track('review_cta_clicked', { source: source });
      var base = apiBase();
      if (!base) return;
      fetch(base + '/app/review/click', {
        method: 'POST',
        keepalive: true,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          session_token: sessionToken() || undefined,
          quote_id: surveyQuoteId(ship) || undefined,
          source: source,
        }),
      }).catch(function () {});
    };

    var card = function (children) {
      return React.createElement('div', {
        onMouseDown: function (e) { e.stopPropagation(); },
        style: { width: '100%', maxWidth: 460, background: T.paper || '#F4F5F7', borderRadius: 22, overflow: 'hidden', boxShadow: '0 24px 70px rgba(0,0,0,0.4)', maxHeight: '92vh', display: 'flex', flexDirection: 'column' },
      }, children);
    };
    var header = function (kicker, title) {
      return React.createElement('div', { key: 'h', style: { background: T.navy, padding: '22px 24px 20px', position: 'relative' } }, [
        React.createElement('button', { key: 'x', onClick: close, 'aria-label': 'Close', style: { position: 'absolute', top: 16, right: 16, width: 32, height: 32, borderRadius: 9, border: 0, background: 'rgba(255,255,255,0.1)', color: '#fff', cursor: 'pointer' } }, '✕'),
        React.createElement('div', { key: 'k', style: { fontFamily: FM, fontSize: 10.5, letterSpacing: '.14em', textTransform: 'uppercase', color: T.red, fontWeight: 700 } }, kicker),
        React.createElement('div', { key: 't', style: { fontFamily: FD, fontWeight: 900, fontSize: 21, color: '#fff', letterSpacing: '-.01em', marginTop: 6, lineHeight: 1.2 } }, title),
        ship && ship.cargo ? React.createElement('div', { key: 's', style: { fontFamily: FB, fontSize: 12.5, color: 'rgba(255,255,255,0.65)', marginTop: 5 } }, ship.cargo + (ship.to ? ' · ' + ship.to : '')) : null,
      ].filter(Boolean));
    };

    if (phase === 'thanks-high') {
      return card([
        header('Thank you', 'Glad we delivered for you'),
        React.createElement('div', { key: 'b', style: { padding: '22px 24px 26px', textAlign: 'center' } }, [
          React.createElement('div', { key: 'p', style: { fontFamily: FB, fontSize: 14, color: T.body, lineHeight: 1.55, marginBottom: 18 } }, "A quick Google review helps our family business more than you know. Would you share it?"),
          React.createElement('a', { key: 'g', href: review_url || reviewUrl(), target: '_blank', rel: 'noreferrer', onClick: recordReviewClick, style: { display: 'block', textDecoration: 'none', background: T.red, color: '#fff', borderRadius: 12, padding: '14px 18px', fontFamily: FB, fontWeight: 800, fontSize: 14.5 } }, 'Leave a Google review'),
          React.createElement('button', { key: 'l', onClick: close, style: { marginTop: 10, background: 'transparent', border: 0, color: T.muted, fontFamily: FB, fontWeight: 700, fontSize: 13, cursor: 'pointer' } }, 'Maybe later'),
        ]),
      ]);
    }
    if (phase === 'thanks-low') {
      return card([
        header('Thank you', "We hear you — and we'll make it right"),
        React.createElement('div', { key: 'b', style: { padding: '22px 24px 26px', textAlign: 'center' } }, [
          React.createElement('div', { key: 'p', style: { fontFamily: FB, fontSize: 14, color: T.body, lineHeight: 1.55, marginBottom: 18 } }, "Thank you for the honest feedback. Your Viamar agent will reach out personally to put things right."),
          React.createElement('button', { key: 'c', onClick: function () { close(); if (window.ViamarChat && window.ViamarChat.open) window.ViamarChat.open({ reason: 'survey_followup', source: 'survey' }); }, style: { width: '100%', border: 0, background: T.navy, color: '#fff', borderRadius: 12, padding: '14px 18px', fontFamily: FB, fontWeight: 800, fontSize: 14.5, cursor: 'pointer' } }, 'Message my agent now'),
          React.createElement('button', { key: 'l', onClick: close, style: { marginTop: 10, background: 'transparent', border: 0, color: T.muted, fontFamily: FB, fontWeight: 700, fontSize: 13, cursor: 'pointer' } }, 'Close'),
        ]),
      ]);
    }

    // form
    var sending = phase === 'sending';
    return card([
      header('How did we do?', 'Rate your Viamar experience'),
      React.createElement('div', { key: 'b', style: { padding: '20px 24px 24px', overflowY: 'auto' } }, [
        React.createElement(Stars, { key: 'st', value: rating, onPick: setRating }),
        rating ? React.createElement('div', { key: 'rl', style: { textAlign: 'center', fontFamily: FB, fontWeight: 700, fontSize: 13, color: rating >= 4 ? (T.green || '#2E8B6F') : (T.amber || '#E0922F'), marginBottom: 16 } }, rating >= 4 ? 'Great to hear!' : 'Thanks — tell us what went wrong') : React.createElement('div', { key: 'rl', style: { textAlign: 'center', fontFamily: FB, fontSize: 12.5, color: T.muted, marginBottom: 16 } }, 'Tap to rate'),
        rating ? React.createElement('div', { key: 'tg', style: { display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 16 } },
          TAGS.map(function (t) {
            var on = tags.indexOf(t) >= 0;
            return React.createElement('button', { key: t, onClick: function () { toggleTag(t); }, style: { border: '1.5px solid ' + (on ? T.red : T.line2), background: on ? 'rgba(221,28,36,0.07)' : '#fff', color: on ? T.ink : T.muted, borderRadius: 999, padding: '8px 13px', fontFamily: FB, fontWeight: 700, fontSize: 12.5, cursor: 'pointer' } }, t);
          })
        ) : null,
        rating ? React.createElement('textarea', { key: 'cm', value: comment, onChange: function (e) { setComment(e.target.value); }, placeholder: 'Anything you’d like to add? (optional)', rows: 3, style: { width: '100%', boxSizing: 'border-box', border: '1.5px solid ' + T.line, borderRadius: 12, padding: '12px 14px', fontSize: 15, fontFamily: FB, color: T.ink, outline: 'none', resize: 'vertical', marginBottom: 14 } }) : null,
        (rating >= 4) ? React.createElement('label', { key: 'cn', style: { display: 'flex', gap: 10, alignItems: 'flex-start', cursor: 'pointer', marginBottom: 16 } }, [
          React.createElement('input', { key: 'i', type: 'checkbox', checked: consent, onChange: function (e) { setConsent(e.target.checked); }, style: { marginTop: 2 } }),
          React.createElement('span', { key: 's', style: { fontFamily: FB, fontSize: 12, color: T.muted, lineHeight: 1.45 } }, 'Viamar may share my feedback as a testimonial.'),
        ]) : null,
        phase === 'error' ? React.createElement('div', { key: 'err', role: 'alert', style: { marginBottom: 12, color: T.red, fontFamily: FB, fontSize: 12.5, lineHeight: 1.45 } }, 'We could not save your feedback yet. Please try again, or message your Viamar contact for help.') : null,
        React.createElement('button', { key: 'sub', onClick: submit, disabled: !rating || sending, style: { width: '100%', border: 0, borderRadius: 12, padding: '14px 18px', background: (!rating || sending) ? T.line : T.red, color: '#fff', fontFamily: FB, fontWeight: 800, fontSize: 14.5, cursor: (!rating || sending) ? 'default' : 'pointer' } }, sending ? 'Sending…' : 'Submit feedback'),
      ].filter(Boolean)),
    ]);
  }

  function Backdrop(props) {
    return React.createElement('div', {
      onMouseDown: function (e) { if (e.target === e.currentTarget) close(); },
      style: { position: 'fixed', inset: 0, zIndex: 9980, background: 'rgba(6,16,28,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 },
    }, React.createElement(SurveyModal, props));
  }

  function ensureRoot() {
    if (!root) { host = document.createElement('div'); host.id = 'viamar-survey-host'; document.body.appendChild(host); root = ReactDOM.createRoot(host); }
    return root;
  }
  function close() { if (root) root.render(null); }
  function open(opts) {
    opts = opts || {};
    if (window.ViamarAnalytics) ViamarAnalytics.track('survey_opened', { source: opts.source || 'app' });
    ensureRoot().render(React.createElement(Backdrop, { ship: opts.ship || null, source: opts.source || 'app' }));
  }

  window.ViamarSurvey = { open: open, close: close };
})();
