/* eslint-disable */
;(function(){
const DS = window.Ds2026DesignSystem_dc290c;
const { VeganBadge, StatusChip, EditButton, ReorderHandle } = DS;
const { useSelectedPlacePhoto } = window.JP2026Detail;

const FOOD_CATEGORIES = new Set([
  'food', 'restaurant', 'cafe', 'café', 'bakery', 'ramen', 'dessert', 'bar',
  'מסעדה', 'בית קפה', 'מאפייה', 'ראמן', 'אוכל', 'אוכל רחוב', 'קינוחים', 'קפה', 'בר',
]);

function isMealActivity(activity) {
  const category = String(activity && activity.cat || '').trim().toLowerCase();
  return FOOD_CATEGORIES.has(category) || Boolean(activity && activity.meal_slot);
}

/* PURE_TIMELINE_LOGIC_START */
function representativePhotoPlace(destination) {
  const resolved = destination && Array.isArray(destination.destinations) ? destination.destinations : [];
  const orderedStop = resolved.find(entry => entry && entry.role !== 'option' && entry.place);
  return (orderedStop || resolved.find(entry => entry && entry.place) || {}).place || null;
}

function timelineCardInteractionModel(destination, editing, callbacks, activity, index) {
  const mode = destination && destination.mode;
  const tappable = mode === 'direct' || mode === 'group';
  const handlers = callbacks || {};
  return {
    tappable,
    showEdit: Boolean(editing && typeof handlers.onEdit === 'function'),
    showReorder: Boolean(editing && typeof handlers.onReorderPointerDown === 'function'),
    activity,
    index,
    onOpen:handlers.onOpen,
    onEdit:handlers.onEdit,
    onReorderPointerDown:handlers.onReorderPointerDown,
  };
}

function invokeTimelineOpen(model, event) {
  if (model && model.tappable && typeof model.onOpen === 'function') model.onOpen(model.activity, model.index, event);
}

function invokeTimelineEdit(model, event) {
  if (event && typeof event.stopPropagation === 'function') event.stopPropagation();
  if (model && model.showEdit) model.onEdit(model.activity, model.index, event);
}

function invokeTimelineReorder(model, event) {
  if (model && model.showReorder) model.onReorderPointerDown(event, model.activity, model.index);
}

function persistentPlaceCover(place) {
  if (!place) return '';
  return place.cover_asset?.url || place.photo_url || '';
}

function shouldShowPlaceLabel(activity) {
  const place = String(activity && activity.place || '').trim();
  if (!place) return false;
  const label = String(activity && activity.label || '').trim();
  return !label.toLocaleLowerCase().includes(place.toLocaleLowerCase());
}

function mealCardTitle(activity) {
  const slot = String(activity && activity.meal_slot || '').trim().toLowerCase();
  if (slot === 'breakfast') return 'ארוחת בוקר';
  if (slot === 'lunch') return 'ארוחת צהריים';
  if (slot === 'dinner') return 'ארוחת ערב';
  const label = String(activity && activity.label || '').trim();
  if (/ארוחת בוקר|^בוקר$/u.test(label)) return 'ארוחת בוקר';
  if (/ארוחת צהריים|^צהריים$/u.test(label)) return 'ארוחת צהריים';
  if (/ארוחת ערב|^ערב$/u.test(label)) return 'ארוחת ערב';
  return label || 'ארוחה';
}

function mealCardPlace(activity, resolvedPlace) {
  const explicit = String(activity && activity.place || '').trim();
  if (explicit) return explicit;
  const resolved = String(resolvedPlace && resolvedPlace.name || '').trim();
  if (resolved) return resolved;
  const label = String(activity && activity.label || '').trim();
  const separator = label.indexOf('·');
  return separator >= 0 ? label.slice(separator + 1).trim() : '';
}

function photoAuthors(photo) {
  const authors = photo && Array.isArray(photo.authorAttributions) ? photo.authorAttributions : [];
  const normalized = authors.map(author => ({
    displayName:String(author && author.displayName || '').trim(),
    uri:String(author && author.uri || '').trim(),
  })).filter(author => author.displayName);
  if (normalized.length) return normalized;
  const fallback = String(photo && (photo.author || photo.author_name) || '').trim();
  return fallback ? [{ displayName:fallback, uri:'' }] : [];
}

function buildPhotoBoxModel(place, liveState, options) {
  const opts = options || {};
  const persistentUrl = persistentPlaceCover(place);
  const live = liveState || { status:'idle', url:'', photo:null, sourceUri:'' };
  const status = persistentUrl ? 'ready' : (!place || !place.place_id ? 'missing' : live.status || 'idle');
  const url = persistentUrl || live.url || '';
  const photo = persistentUrl ? (place.cover_asset || {}) : live.photo;
  const authors = photoAuthors(photo);
  const author = authors.map(entry => entry.displayName).join(', ');
  const source = persistentUrl
    ? String(photo && (photo.sourceUri || photo.source_uri || photo.source || photo.provider) || '').trim()
    : String(live.sourceUri || '').trim();
  const failed = status === 'error';
  const name = place && place.name || 'המקום';
  return {
    status, url, photo, authors, author, source,
    provider:persistentUrl ? String(photo && photo.provider || '').trim() : (status === 'ready' ? 'Google Places' : ''),
    persistent:Boolean(persistentUrl),
    googleAttribution:!persistentUrl && status === 'ready' && Boolean(url),
    attributionLabel:author ? `Google Places, ${author}` : 'Google Places',
    detailLinks:!persistentUrl && status === 'ready' && url ? [
      ...(source ? [{ label:'Google', href:source, kind:'source' }] : [{ label:'Google', href:'', kind:'source' }]),
      ...authors.map(entry => ({ label:entry.displayName, href:entry.uri, kind:'author' })),
    ] : [],
    ariaLabel:failed ? `התצלום של ${name} לא נטען`
      : status === 'missing' ? `אין תצלום ל${name}`
      : author ? `תצלום של ${name}, ${author}` : `תצלום של ${name}`,
    errorCopy:failed ? 'התצלום לא נטען' : '',
    dimensions:{
      width:opts.detail ? '100%' : (opts.size == null ? 60 : opts.size),
      height:opts.detail ? 'auto' : (opts.size == null ? 60 : opts.size),
      aspectRatio:opts.detail ? '16 / 10' : '1 / 1',
      borderRadius:opts.radius == null ? 12 : opts.radius,
    },
  };
}
/* PURE_TIMELINE_LOGIC_END */

function categoryPhotoTint(place, fallback) {
  const category = String(place && place.cat || '').trim().toLowerCase();
  if (FOOD_CATEGORIES.has(category)) return 'var(--matcha-tint)';
  if (/train|transit|rail|flight|רכבת|מעבר|טיס/.test(category)) return 'var(--sky-tint)';
  if (/shop|market|קניות|שוק/.test(category)) return 'var(--peach-tint)';
  if (/nature|park|garden|temple|טבע|פארק|גן|מקדש/.test(category)) return 'var(--matcha-tint)';
  return fallback;
}

function PhotoBox({ place, tint='var(--surface-card-2)', size=60, radius=12, className='', detail=false }) {
  const persistentUrl = persistentPlaceCover(place);
  const live = useSelectedPlacePhoto(
    place && place.place_id || '',
    place && place.google_photo_index,
    480,
    Boolean(place && !persistentUrl)
  );
  const model = buildPhotoBoxModel(place, live, { size, radius, detail });
  const { status, url, author, source } = model;
  const emoji = place && place.icon || '📍';
  const tileTint = categoryPhotoTint(place, tint);
  const common = model.dimensions;

  if (status === 'loading' || status === 'idle') {
    return <span className={`jp-photo-box jp-shimmer ${className}`} role="status" aria-label="טוען תצלום…"
      style={{ ...common, flex:'0 0 auto', display:'block', background:tileTint }} />;
  }
  if (status === 'ready' && url) {
    return <span className="jp-photo-stack" style={{ flex:'0 0 auto', width:common.width, minWidth:0, display:'flex', flexDirection:'column', gap:3 }}>
      <span className={`jp-photo-box ${className}`} data-photo-provider={model.provider || undefined}
        data-photo-source={source || undefined} data-photo-author={author || undefined}
        style={{ ...common, display:'block', overflow:'hidden', background:tileTint }}>
        <img src={url} alt={model.googleAttribution ? `${model.ariaLabel}, ${model.attributionLabel}` : model.ariaLabel}
          loading="lazy" decoding="async" style={{ width:'100%', height:'100%', objectFit:'cover', display:'block' }} />
      </span>
      {model.googleAttribution && detail && <span aria-label={model.attributionLabel}
        style={{ padding:'2px 4px', display:'flex', gap:5, flexWrap:'wrap', color:'var(--ink-700)',
          fontFamily:'var(--font-ui)', fontSize:10, lineHeight:1.3 }}>
        {model.detailLinks.map((link,index)=><React.Fragment key={`${link.kind}-${index}`}>
          {index > 0 && <span aria-hidden="true">·</span>}
          {link.href
            ? <a href={link.href} target="_blank" rel="noopener noreferrer" onClick={(event)=>event.stopPropagation()}
                style={{ color:'inherit', textDecoration:'underline' }}>{link.label}</a>
            : <span>{link.label}</span>}
        </React.Fragment>)}
      </span>}
    </span>;
  }
  const failed = status === 'error';
  return <span className={`jp-photo-box ${className}`} role="img"
    aria-label={model.ariaLabel}
    style={{ ...common, flex:'0 0 auto', display:'grid', placeItems:'center', alignContent:'center', gap:1,
      overflow:'hidden', padding:4, textAlign:'center', background:tileTint, color:'var(--ink-700)' }}>
    <span aria-hidden="true" style={{ fontSize:detail?34:22, lineHeight:1 }}>{emoji}</span>
    {failed && <span style={{ fontFamily:'var(--font-ui)', fontSize:detail?12:8, lineHeight:1.05 }}>{model.errorCopy}</span>}
  </span>;
}

function Time({ children, muted }) {
  return <span className="time-range" style={{ fontFamily:'var(--font-ui)', fontSize:14,
    color:muted?'var(--ink-500)':'var(--ink-900)', letterSpacing:.3 }}>{children}</span>;
}

function TimelineCard({ activity, destination, accent, tint, deep, status='later', last=false, editing=false, index=null,
  onOpen, onEdit, onReorderPointerDown }) {
  const act = activity || {};
  const resolved = destination || act.destination || { mode:'none', destinations:[] };
  const interaction = timelineCardInteractionModel(resolved, editing, { onOpen, onEdit, onReorderPointerDown }, act, index);
  const tappable = interaction.tappable;
  const meal = isMealActivity(act);
  const done = status === 'done';
  const next = status === 'next';
  const booking = act.kind === 'booking';
  const place = representativePhotoPlace(resolved);
  const chips = act.chips || [];
  const displayTitle = meal ? mealCardTitle(act) : act.label;
  const displayPlace = meal ? mealCardPlace(act, place) : (shouldShowPlaceLabel(act) ? act.place : '');
  const content = <>
    {tappable && <PhotoBox place={place} tint={tint} />}
    <span style={{ flex:1, minWidth:0, display:'flex', flexDirection:'column', alignSelf:'stretch', justifyContent:'center' }}>
      <span style={{ display:'flex', alignItems:'center', gap:7, minWidth:0 }}>
        {meal
          ? <span aria-hidden="true" style={{ flex:'0 0 auto', width:30, height:30, borderRadius:'50%', background:'var(--matcha-tint)', display:'grid', placeItems:'center', fontSize:16 }}>{act.icon}</span>
          : <span aria-hidden="true" style={{ fontSize:16 }}>{act.icon}</span>}
        <span style={{ minWidth:0, fontFamily:'var(--font-ui)', fontSize:16, color:'var(--ink-900)' }}>{displayTitle}</span>
        {booking && <span style={{ marginInlineStart:'auto', fontSize:11, color:deep, background:tint, padding:'2px 8px', borderRadius:999, whiteSpace:'nowrap' }}>הזמנה 🎟️</span>}
        {done && <span aria-hidden="true" style={{ marginInlineStart:booking?4:'auto', color:'var(--matcha-deep)', fontSize:15 }}>✓</span>}
      </span>
      {meal && <span aria-hidden="true" style={{ borderTop:'1.5px dashed var(--hairline)', margin:'7px 0 0' }} />}
      <span style={{ display:'flex', alignItems:'center', gap:8, marginTop:meal?6:3, flexWrap:'wrap' }}>
        {displayPlace && <span className="ltr" style={{ fontSize:12.5, color:'var(--ink-500)' }}>{displayPlace}</span>}
      </span>
      {Boolean(act.vegan || chips.length) && <span style={{ display:'flex', gap:6, marginTop:7, flexWrap:'wrap' }}>
        {act.vegan && <VeganBadge status={act.vegan} />}
        {chips.map((chip,index)=><StatusChip key={index} preset={chip && chip.preset || chip} />)}
      </span>}
      {tappable && <span style={{ marginTop:5, color:deep, fontFamily:'var(--font-ui)', fontSize:11 }}>לפרטים ‹</span>}
    </span>
  </>;
  const cardStyle = { appearance:'none', textAlign:'start', flex:1, minWidth:0, marginBottom:12, position:'relative',
    display:'flex', alignItems:'center', gap:10, width:'100%', background:meal?'var(--surface-white)':'var(--surface-card)',
    border:next?`1.5px solid ${accent}`:(meal?'1px solid var(--hairline)':(booking?`1.5px solid ${accent}`:'var(--border-card)')),
    borderTop:meal?'none':undefined, borderRadius:meal?'0 0 14px 14px':'var(--r-md)', padding:10,
    boxShadow:'var(--shadow-sm)', color:'inherit', opacity:1, cursor:tappable?'pointer':'default' };
  const row = <div className="jp-timeline-row" data-status={status} style={{ display:'flex', gap:12, opacity:done ? .55 : 1, flex:1, minWidth:0 }}>
    <div className="jp-timeline-rail" style={{ flex:'0 0 44px', display:'flex', flexDirection:'column', alignItems:'center', textAlign:'center' }}>
      <Time muted={!next}>{act.time}</Time>
      <div style={{ marginTop:8, width:meal||next?16:12, height:meal||next?16:12, borderRadius:'50%',
        background:done?'var(--ink-300)':(meal?'var(--peach-deep)':accent), border:'2px solid var(--surface-card)',
        boxShadow:meal&&!done?'0 0 0 4px var(--peach-tint)':(next?`0 0 0 4px ${tint}`:'none'), flex:'0 0 auto', zIndex:1 }} />
      {!last && <div style={{ flex:'1 1 auto', width:0, borderInlineStart:'2px dotted var(--route-dot)', minHeight:10 }} />}
    </div>
    {tappable
      ? <button type="button" className="jp-timeline-card jp-interactive-card" onClick={(event)=>invokeTimelineOpen(interaction, event)}
          aria-label={`פתיחת פרטים עבור ${act.label || act.place || ''}`} style={cardStyle}>
          {meal && <span aria-hidden="true" style={{ position:'absolute', top:-1, insetInline:-1, height:7, pointerEvents:'none', background:'radial-gradient(circle at 6px -2px, transparent 6px, var(--surface-white) 6px)', backgroundSize:'12px 7px', backgroundRepeat:'repeat-x', filter:'drop-shadow(0 -1px 0 var(--hairline))' }} />}
          {content}
        </button>
      : <div className="jp-timeline-card" style={cardStyle}>{content}</div>}
  </div>;
  return <div className="jp-timeline-entry" style={{ display:'flex', alignItems:'flex-start', gap:editing?6:0 }}>
    {(interaction.showEdit || interaction.showReorder) && <div className="jp-timeline-edit-strip" aria-label="פקדי עריכה"
      style={{ flex:'0 0 30px', paddingTop:18, display:'grid', gap:8, justifyItems:'center' }}>
      {interaction.showReorder && <ReorderHandle onPointerDown={(event)=>invokeTimelineReorder(interaction, event)} />}
      {interaction.showEdit && <EditButton size={28} onClick={(event)=>invokeTimelineEdit(interaction, event)} />}
    </div>}
    {row}
  </div>;
}

window.JP2026Timeline = { TimelineCard, PhotoBox, FOOD_CATEGORIES, isMealActivity, representativePhotoPlace,
  timelineCardInteractionModel, invokeTimelineOpen, invokeTimelineEdit, invokeTimelineReorder,
  persistentPlaceCover, shouldShowPlaceLabel, mealCardTitle, mealCardPlace, buildPhotoBoxModel, categoryPhotoTint };
})();
