/* Viamar — funnel engine: the single "next step" for authed customers +
   the anonymous path chooser. Every surface renders ONE obvious next action
   so nobody gets stuck (insurance-app style).

   window.ViamarNextStep = { nextStepFor, NextStepCard, PathChooser }

   Milestone model (7 steps, mined from real GHL threads — see
   docs/ghl-process-mining-2026-06-12.md and app/store.js applyMilestones):
   1 Quote ready · 2 Booked · 3 Documents complete · 4 Loaded ·
   5 On the water · 6 Arrived / agent handoff · 7 Delivered. */

// Google review link — SINGLE place to edit once the real g.page slug exists.
if (!window.VIAMAR_REVIEW_URL) window.VIAMAR_REVIEW_URL = 'https://www.google.com/search?q=Viamar+Scilla+Transport+International+INC+Reviews&si=AL3DRZHrmvnFAVQPOO2Bzhf8AX9KZZ6raUI_dT7DG_z0kV2_xxVJxPqWFYe69kxOmNhVUULT-mRfCDT_i-KnjduBNgJh2-R_iMsQqSiMgYK9wsM3kS5aWXNe-MNvieLVXDyEaPIUnpIdoegPTMVJXCnbiNRbrKYlZPUdCqSbd2pHoIKpU5Zxpv4%3D';

// Resolve the effective milestone for a customer-shaped shipment. Quotes with
// real milestone history carry `currentMilestone` (store.js overlay); rows
// without it fall back from `kind` so a milestone-less booked/transit/delivered
// shipment never shows "we're reviewing".
function nextStepMilestone(ship) {
  var m = Number(ship && ship.currentMilestone) || 0;
  if (m >= 1 && m <= 7) return m;
  var kind = ship && ship.kind;
  if (kind === 'delivered') return 7;
  if (kind === 'transit') return 5;
  if (kind === 'booked') return 2;
  return 1; // review / unknown → quote under review
}

// Pure function: shipment → { milestone, icon, label, sub, action }.
// action = { type: 'call'|'docs'|'track'|'review', label, href? } — the
// renderer maps type onto whatever surfaces the caller actually has.
function nextStepFor(ship) {
  var effectiveMilestone = nextStepMilestone(ship);
  if (ship && effectiveMilestone <= 1 && ship.customerStatus === 'quote_ready') return {
    milestone: 1,
    icon: 'doc',
    label: 'Your quote is ready',
    sub: ship.nextAction || 'Review the released price and conditions.',
    actionOwner: 'none',
    action: { type: 'track', label: 'View quote' },
  };
  if (ship && effectiveMilestone <= 1 && ship.nextAction && ship.nextActionOwner === 'customer') {
    var nextAction = typeof ship.nextAction === 'string'
      ? { title: 'Next step', detail: ship.nextAction }
      : ship.nextAction;
    return {
      milestone: 0,
      icon: 'arrowR',
      label: nextAction.title || 'Tell us a little more',
      sub: nextAction.detail || 'One short step helps your Viamar agent prepare the request.',
      actionOwner: 'customer',
      action: { type: 'details', label: 'Continue' },
    };
  }
  if (ship && effectiveMilestone <= 1 && ship.nextAction && ship.nextActionOwner === 'viamar') return {
    milestone: 1,
    icon: 'clock',
    label: 'Viamar is working on your request',
    sub: typeof ship.nextAction === 'string'
      ? ship.nextAction
      : ship.nextAction.detail || ship.nextAction.title,
    actionOwner: 'viamar',
    action: { type: 'track', label: 'View status' },
  };
  if (ship && effectiveMilestone <= 1 && ship.nextAction) {
    var unownedAction = typeof ship.nextAction === 'string'
      ? { title: 'Next step', detail: ship.nextAction }
      : ship.nextAction;
    return {
      milestone: 0,
      icon: 'arrowR',
      label: unownedAction.title || 'Tell us a little more',
      sub: unownedAction.detail || 'One short step helps your Viamar agent prepare the request.',
      actionOwner: 'customer',
      action: { type: 'details', label: 'Continue' },
    };
  };
  var m = effectiveMilestone;
  if (m <= 1) return {
    milestone: 1, icon: 'clock',
    label: "We're reviewing your request — reply within one business day",
    sub: 'Need it faster? Call 1-800-277-7570 · Mon–Fri 8am–5pm ET',
    action: { type: 'call', label: 'Call us', href: 'tel:18002777570' },
  };
  if (m === 2) return {
    milestone: 2, icon: 'doc',
    label: 'Next: documents',
    sub: 'Ownership / packing list — send them to your agent to keep things moving',
    action: { type: 'docs', label: 'Send documents' },
  };
  if (m === 3) {
    var week = ship && ship.consolidation ? String(ship.consolidation) : null;
    return {
      milestone: 3, icon: 'box',
      label: 'Consolidation in progress',
      sub: week
        ? week.charAt(0).toUpperCase() + week.slice(1) + ' — nothing needed from you'
        : "We're scheduling your loading — nothing needed from you",
      action: { type: 'track', label: 'View timeline' },
    };
  }
  if (m === 4) return {
    milestone: 4, icon: 'camera',
    label: 'View your loading photos',
    sub: 'Loaded and secured at our warehouse — every load is photographed',
    action: { type: 'track', label: 'View photos' },
  };
  if (m === 5) return {
    milestone: 5, icon: 'ship',
    label: 'On the water',
    sub: (ship && ship.vessel && ship.vessel !== 'Pending assignment' ? ship.vessel + ' · ' : '') + 'ETA ' + ((ship && ship.eta) || 'updating'),
    action: { type: 'track', label: 'Track voyage' },
  };
  if (m === 6) return {
    milestone: 6, icon: 'phone',
    label: 'Arrival + delivery coordination',
    sub: 'Our destination agent will contact you — keep your phone handy',
    action: { type: 'track', label: 'View status' },
  };
  return {
    milestone: 7, icon: 'star',
    label: 'How did we do? Rate your delivery',
    sub: 'Delivered — a quick rating helps our family business a lot',
    action: { type: 'survey', label: 'Rate your experience' },
  };
}

function GuidanceRow({ label, value, emphasis }) {
  return (
    <div style={{ minWidth: 0 }}>
      <div style={{ fontFamily: FM, fontSize: 8.5, fontWeight: 700, letterSpacing: 0.7, textTransform: 'uppercase', color: T.faint, marginBottom: 3 }}>{label}</div>
      <div style={{ fontFamily: FB, fontSize: 12.5, fontWeight: emphasis ? 800 : 650, color: emphasis ? T.red : T.ink, lineHeight: 1.4 }}>{value}</div>
    </div>
  );
}

/* The single next-step card — FIRST element for authed customers with ≥1
   quote. Red accent, one icon, one label, one action. `compact` swaps the
   button for a chevron (mobile). */
function NextStepCard({ ship, onTrack, onChat, compact, style }) {
  var step = nextStepFor(ship);
  var guidance = window.ViamarJourneyGuidance
    ? ViamarJourneyGuidance.resolve(ship)
    : {
        milestone: step.milestone,
        status: step.label,
        nextAction: step.sub,
        nextUpdate: 'We will update you when new information is confirmed.',
        owner: 'Viamar team',
        freshness: null,
        customerActionRequired: false,
        exception: null,
        hasOwner: false,
        hasNextAction: false,
        hasNextUpdate: false,
        hasException: false,
      };
  // Free-text operational guidance cannot safely encode a deep-link target.
  // When Ops publishes a specific next action, offer one honest route back to
  // the assigned team instead of pairing the text with a contradictory static
  // milestone button. Delivered shipments keep the private survey action.
  var cardAction = step.actionOwner === 'none'
    ? step.action
    : guidance.milestone === 7
    ? ((guidance.customerActionRequired || guidance.hasException)
        ? { type: 'contact', label: 'Message your contact' }
        : step.action)
    : (guidance.hasNextAction
        ? (guidance.customerActionRequired
            ? { type: 'contact', label: 'Message your contact' }
            : { type: 'track', label: 'View timeline' })
        : step.action);
  var evidence = window.ViamarJourneyGuidance
    ? ViamarJourneyGuidance.evidence(guidance)
    : {
        milestone: step.milestone,
        guidance_complete: false,
        has_status: Boolean(step.label),
        has_owner: false,
        has_next_action: false,
        has_next_update: false,
        has_exception: false,
        customer_action_required: false,
        survey_ready: step.milestone === 7,
      };
  React.useEffect(function () {
    if (window.ViamarAnalytics) ViamarAnalytics.track('next_step_shown', evidence);
  }, [
    evidence.milestone,
    evidence.guidance_complete,
    evidence.has_status,
    evidence.has_owner,
    evidence.has_next_action,
    evidence.has_next_update,
    evidence.has_exception,
    evidence.customer_action_required,
    evidence.survey_ready,
  ]);
  var go = function () {
    if (window.ViamarAnalytics) ViamarAnalytics.track('next_step_clicked', evidence);
    if (cardAction.type === 'call') { window.location.href = cardAction.href; return; }
    if (cardAction.type === 'contact') {
      var reason = guidance.customerActionRequired ? 'customer_action' : 'status';
      if (onChat) onChat({ reason: reason, source: 'next-step' });
      else if (window.ViamarChat && window.ViamarChat.open) window.ViamarChat.open({ reason: reason, source: 'next-step' });
      else window.location.href = 'tel:18002777570';
      return;
    }
    // Delivered → open the survey, which gates the public Google review
    // (happy → Google, unhappy → routed privately to the agent).
    if (cardAction.type === 'survey') { if (window.ViamarSurvey) window.ViamarSurvey.open({ ship: ship, source: 'next-step' }); else window.open(window.VIAMAR_REVIEW_URL, '_blank'); return; }
    if (cardAction.type === 'review') { window.open(window.VIAMAR_REVIEW_URL, '_blank'); return; }
    if (cardAction.type === 'docs') { if (onChat) onChat({ reason: 'documents', source: 'next-step' }); else if (onTrack) onTrack(); return; }
    if (onTrack) onTrack();
  };
  return (
    <div className="ph-no-capture" style={{ background: '#fff', border: '1px solid rgba(221,28,36,0.25)', borderRadius: 16, padding: compact ? '14px 15px' : '17px 18px', boxShadow: '0 6px 18px rgba(221,28,36,0.1)', ...style }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{ width: compact ? 40 : 44, height: compact ? 40 : 44, borderRadius: 12, background: 'rgba(221,28,36,0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name={step.icon} size={compact ? 20 : 22} color={T.red} stroke={2} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: FM, fontSize: 9, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase', color: T.red, marginBottom: 3 }}>Your shipment guidance</div>
          <div style={{ fontFamily: FB, fontWeight: 800, fontSize: compact ? 14 : 15.5, color: T.ink, lineHeight: 1.25 }}>{guidance.status}</div>
          <div style={{ fontFamily: FM, fontSize: 9.5, color: T.faint, marginTop: 3 }}>
            {guidance.freshness ? 'Status updated ' + guidance.freshness : 'Status update time is not available.'}
          </div>
        </div>
      </div>

      {guidance.exception && (
        <div role="alert" style={{ display: 'flex', gap: 9, alignItems: 'flex-start', marginTop: 13, padding: '10px 11px', borderRadius: 11, background: 'rgba(224,146,47,0.11)', border: '1px solid rgba(224,146,47,0.28)' }}>
          <Icon name="clock" size={16} color={T.amber} stroke={2} />
          <div style={{ fontFamily: FB, fontSize: 12, color: T.body, lineHeight: 1.45 }}>{guidance.exception}</div>
        </div>
      )}

      <div style={{ display: 'grid', gridTemplateColumns: compact ? '1fr' : 'repeat(2, minmax(0, 1fr))', gap: compact ? 11 : '13px 20px', marginTop: 14, paddingTop: 14, borderTop: '1px solid ' + T.line2 }}>
        <GuidanceRow label="Current status" value={guidance.status} />
        <GuidanceRow label="Next action" value={guidance.nextAction} emphasis={guidance.customerActionRequired} />
        <GuidanceRow label="Expected update" value={guidance.nextUpdate} />
        <GuidanceRow label="Your Viamar contact" value={guidance.owner} />
      </div>

      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 14 }}>
        <Btn variant="primary" size="sm" onClick={go} style={{ width: compact ? '100%' : 'auto' }}>{cardAction.label}</Btn>
      </div>
    </div>
  );
}

/* Anonymous decision band — two paths, no dead end: get a quote or sign in
   to track. Sits ABOVE the hero (the hero sells; this routes). `stacked`
   = mobile (cards in a column). */
function PathChooser({ onQuote, onSignIn, stacked }) {
  var choose = function (path, fn) {
    if (window.ViamarAnalytics) ViamarAnalytics.track('funnel_path_chosen', { path: path });
    if (fn) fn();
  };
  return (
    <div style={{ display: 'flex', flexDirection: stacked ? 'column' : 'row', gap: 12 }}>
      <div onClick={() => choose('quote', onQuote)} style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 13, background: T.red, borderRadius: 16, padding: '14px 16px', cursor: 'pointer', boxShadow: '0 8px 22px rgba(221,28,36,0.28)' }}>
        <div style={{ width: 40, height: 40, borderRadius: 11, background: 'rgba(255,255,255,0.16)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name="spark" size={20} color="#fff" stroke={2.2} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: FB, fontWeight: 800, fontSize: 14.5, color: '#fff' }}>Get a new quote</div>
          <div style={{ fontFamily: FM, fontSize: 10, color: 'rgba(255,255,255,0.75)', letterSpacing: 0.3, marginTop: 2 }}>Save your request · guided next steps</div>
        </div>
        <Icon name="chevR" size={19} color="#fff" stroke={2.4} />
      </div>
      <div onClick={() => choose('signin', onSignIn)} style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 13, background: '#fff', border: '1.5px solid ' + T.navy, borderRadius: 16, padding: '14px 16px', cursor: 'pointer', boxShadow: '0 1px 2px rgba(10,27,46,0.06)' }}>
        <div style={{ width: 40, height: 40, borderRadius: 11, background: T.paper, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name="user" size={20} color={T.navy} stroke={2} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: FB, fontWeight: 800, fontSize: 14.5, color: T.navy }}>Already shipping with us?</div>
          <div style={{ fontFamily: FM, fontSize: 10, color: T.muted, letterSpacing: 0.3, marginTop: 2 }}>Sign in to track your shipment</div>
        </div>
        <Icon name="chevR" size={19} color={T.navy} stroke={2.4} />
      </div>
    </div>
  );
}

window.ViamarNextStep = { nextStepFor: nextStepFor, NextStepCard: NextStepCard, PathChooser: PathChooser };
