// ===== PARC-EX CARTE — UI Components (Playful) =====
const { useState, useEffect } = React;

/* ---- Category SVG Icons ---- */
var CAT_ICONS = {
  cart: function(color) {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke={color || 'currentColor'} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="9" cy="21" r="1.5"/><circle cx="20" cy="21" r="1.5"/>
        <path d="M1 1h4l2.68 13.39a2 2 0 002 1.61h9.72a2 2 0 002-1.61L23 6H6"/>
      </svg>
    );
  },
  utensils: function(color) {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke={color || 'currentColor'} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
        <path d="M3 2v7c0 1.1.9 2 2 2h4a2 2 0 002-2V2"/><path d="M7 2v20"/>
        <path d="M21 15V2a5 5 0 00-5 5v6c0 1.1.9 2 2 2h3zm0 0v7"/>
      </svg>
    );
  },
  coffee: function(color) {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke={color || 'currentColor'} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
        <path d="M17 8h1a4 4 0 010 8h-1"/><path d="M3 8h14v9a4 4 0 01-4 4H7a4 4 0 01-4-4V8z"/>
        <line x1="6" y1="2" x2="6" y2="4"/><line x1="10" y1="2" x2="10" y2="4"/><line x1="14" y1="2" x2="14" y2="4"/>
      </svg>
    );
  },
  croissant: function(color) {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke={color || 'currentColor'} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
        <path d="M4.6 13.11L10 18.5l5.4-5.39a4.48 4.48 0 00-6.36-6.36L7.6 8.19"/>
        <path d="M1 1l3.6 3.6M22 22l-3-3"/>
        <path d="M16.26 7.74a4.47 4.47 0 01.74 2.5 4.5 4.5 0 01-1.32 3.18L10.5 18.5l-1-1"/>
        <path d="M14 4l3 3"/>
      </svg>
    );
  },
  medkit: function(color) {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke={color || 'currentColor'} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
        <rect x="3" y="7" width="18" height="14" rx="2"/><path d="M8 7V5a2 2 0 012-2h4a2 2 0 012 2v2"/>
        <line x1="12" y1="11" x2="12" y2="17"/><line x1="9" y1="14" x2="15" y2="14"/>
      </svg>
    );
  },
  tree: function(color) {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke={color || 'currentColor'} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
        <path d="M12 3L4 14h4l-2 7h12l-2-7h4L12 3z"/>
      </svg>
    );
  },
  bubbles: function(color) {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke={color || 'currentColor'} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="9" cy="9" r="6"/><circle cx="18" cy="16" r="4"/>
        <circle cx="6" cy="19" r="2.5"/>
      </svg>
    );
  },
  star: function(color) {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke={color || 'currentColor'} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
        <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>
      </svg>
    );
  },
  bus: function(color) {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke={color || 'currentColor'} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
        <rect x="4" y="3" width="16" height="16" rx="3"/><line x1="4" y1="11" x2="20" y2="11"/>
        <line x1="12" y1="3" x2="12" y2="11"/>
        <circle cx="7.5" cy="15.5" r="1"/><circle cx="16.5" cy="15.5" r="1"/>
        <path d="M4 19h16"/>
      </svg>
    );
  },
  pin: function(color) {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke={color || 'currentColor'} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
        <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0118 0z"/>
        <circle cx="12" cy="10" r="3"/>
      </svg>
    );
  }
};

function CatIcon({ icon, color, size }) {
  var sz = size || 16;
  var renderer = CAT_ICONS[icon] || CAT_ICONS.pin;
  return (
    <span style={{ width: sz, height: sz, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
      {renderer(color)}
    </span>
  );
}

/* ---- Check icon ---- */
function CheckIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3.5"
         strokeLinecap="round" strokeLinejoin="round">
      <polyline points="20 6 9 17 4 12"></polyline>
    </svg>
  );
}

/* ---- Language Toggle ---- */
function LangToggle({ lang, onChange }) {
  return (
    <div className="lang-tog">
      <button className={'lang-btn' + (lang === 'fr' ? ' on' : '')} onClick={() => onChange('fr')}>FR</button>
      <button className={'lang-btn' + (lang === 'en' ? ' on' : '')} onClick={() => onChange('en')}>EN</button>
    </div>
  );
}

/* ---- Filter Pills ---- */
function FilterBar({ cats, filter, onFilter, counts, editMode, onAddCat, lang }) {
  var total = 0;
  Object.keys(counts).forEach(function (k) { total += counts[k]; });
  return (
    <div className="filters">
      <button className={'pill' + (filter === 'all' ? ' on' : '')} onClick={() => onFilter('all')}>
        {UI_TEXT[lang].all} {total}
      </button>
      {cats.map(function (c) {
        var n = counts[c.id] || 0;
        if (!n && !editMode) return null;
        return (
          <button key={c.id}
            className={'pill' + (filter === c.id ? ' on' : '')}
            onClick={() => onFilter(c.id)}>
            <span className="pill-icon">
              <CatIcon icon={c.icon || 'pin'} color={filter === c.id ? '#fff' : c.color} size={14} />
            </span>
            {c[lang]}{n > 0 ? ' ' + n : ''}
          </button>
        );
      })}
      {editMode && (
        <button className="pill pill-add" onClick={onAddCat}>+ {UI_TEXT[lang].addCat}</button>
      )}
    </div>
  );
}

/* ---- Open Now Badge ---- */
function OpenBadge({ hours, lang }) {
  var status = isOpenNow(hours);
  if (status === null) return null;
  var t = UI_TEXT[lang];
  return (
    <span className={'open-badge' + (status ? ' open' : ' closed')}>
      <span className="open-dot"></span>
      {status ? t.openNow : t.closedNow}
    </span>
  );
}

/* ---- Sort Toggle ---- */
function SortToggle({ sort, onToggle, lang }) {
  var t = UI_TEXT[lang];
  return (
    <div className="sort-tog">
      <button className={'sort-btn' + (sort === 'cat' ? ' on' : '')} onClick={function () { onToggle('cat'); }}>
        {t.sortCat}
      </button>
      <button className={'sort-btn' + (sort === 'dist' ? ' on' : '')} onClick={function () { onToggle('dist'); }}>
        {t.sortDist}
      </button>
    </div>
  );
}

/* ---- Place Card ---- */
function PlaceCard({ place, cat, active, visited, editMode, lang, walkMin, onClick, onVisit, onEdit, onDel }) {
  var t = UI_TEXT[lang];
  var glink = 'https://www.google.com/maps/dir/?api=1&destination=' + encodeURIComponent(place.addr);
  var short = place.addr.replace(', Montréal', '');
  var bgColor = cat.color + '14'; // 8% opacity
  return (
    <div className={'card' + (active ? ' active' : '') + (visited ? ' visited' : '')}
         style={{ '--cc': cat.color }} onClick={onClick}>
      <div className="card-top">
        <div className="card-icon-wrap" style={{ background: bgColor }}>
          <CatIcon icon={cat.icon || 'pin'} color={cat.color} size={20} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="card-name">{place.name}</div>
          {walkMin !== null && (
            <div className="card-walk">
              {walkMin < 1 ? '< 1' : walkMin}
              <span className="card-walk-unit"> {t.minWalk} {t.walkLabel}</span>
            </div>
          )}
          <div className="card-meta">
            <a className="card-addr" href={glink} target="_blank" rel="noopener"
               onClick={function (e) { e.stopPropagation(); }}>{short}</a>
          </div>
        </div>
        {editMode ? (
          <div className="card-acts">
            <button className="c-act" onClick={function (e) { e.stopPropagation(); onEdit(); }}>{t.editPlace}</button>
            <button className="c-act danger" onClick={function (e) { e.stopPropagation(); onDel(); }}>{t.del}</button>
          </div>
        ) : (
          <button className={'vis-btn' + (visited ? ' on' : '')}
                  title={t.visited}
                  onClick={function (e) { e.stopPropagation(); onVisit(); }}>
            {visited && <CheckIcon />}
          </button>
        )}
      </div>
      {place.hours && (
        <div className="card-hours-row">
          <span className="card-hours">{place.hours}</span>
          <OpenBadge hours={place.hours} lang={lang} />
        </div>
      )}
      {place.note && <div className="card-note">{place.note}</div>}
    </div>
  );
}

/* ---- Place Form (add / edit) ---- */
function PlaceForm({ open, editing, cats, lang, onSave, onCancel }) {
  var t = UI_TEXT[lang];
  var ref = React.useRef(null);
  var _s = function (v) { return v || ''; };
  var _init = function () {
    return { cat: 'restaurant', name: '', addr: '', lat: '', lng: '', hours: '', note: '' };
  };
  var _from = function (p) {
    return { cat: p.cat, name: p.name, addr: p.addr, lat: _s(p.lat), lng: _s(p.lng), hours: _s(p.hours), note: _s(p.note) };
  };
  var [f, setF] = useState(_init);

  useEffect(function () {
    setF(editing ? _from(editing) : _init());
  }, [editing, open]);

  useEffect(function () {
    if (!open) return;
    var handler = function (e) {
      setF(function (prev) { return Object.assign({}, prev, { lat: e.detail.lat.toFixed(6), lng: e.detail.lng.toFixed(6) }); });
    };
    window.addEventListener('map-coord-pick', handler);
    return function () { window.removeEventListener('map-coord-pick', handler); };
  }, [open]);

  var set = function (k, v) { setF(function (prev) { var n = Object.assign({}, prev); n[k] = v; return n; }); };
  var submit = function () {
    if (!f.name.trim() || !f.addr.trim()) return;
    onSave({
      id: editing ? editing.id : undefined,
      cat: f.cat,
      name: f.name.trim(),
      addr: f.addr.trim(),
      lat: parseFloat(f.lat) || null,
      lng: parseFloat(f.lng) || null,
      hours: f.hours.trim(),
      note: f.note.trim()
    });
  };

  return (
    <div className={'form-ov' + (open ? ' open' : '')}
         onClick={function (e) { if (e.target === e.currentTarget) onCancel(); }}>
      <div className="form-sheet" ref={ref}>
        <div className="form-title">{editing ? t.editPlace : t.newPlace}</div>
        <label className="form-lbl">{t.category}</label>
        <select className="form-sel" value={f.cat} onChange={function (e) { set('cat', e.target.value); }}>
          {cats.map(function (c) { return <option key={c.id} value={c.id}>{c[lang]}</option>; })}
        </select>
        <label className="form-lbl">{t.name}</label>
        <input className="form-in" value={f.name} onChange={function (e) { set('name', e.target.value); }}
               placeholder="Bombay Mahal" />
        <label className="form-lbl">{t.address}</label>
        <input className="form-in" value={f.addr} onChange={function (e) { set('addr', e.target.value); }}
               placeholder="1001 Rue Jean-Talon O, Montréal" />
        <label className="form-lbl">{t.coords}</label>
        <div className="form-row">
          <input className="form-in" value={f.lat} onChange={function (e) { set('lat', e.target.value); }}
                 placeholder={t.latitude} type="number" step="any" style={{ flex: 1 }} />
          <input className="form-in" value={f.lng} onChange={function (e) { set('lng', e.target.value); }}
                 placeholder={t.longitude} type="number" step="any" style={{ flex: 1 }} />
        </div>
        {open && <div className="form-hint">{t.mapHint}</div>}
        <label className="form-lbl">{t.hours}</label>
        <input className="form-in" value={f.hours} onChange={function (e) { set('hours', e.target.value); }}
               placeholder="11h–22h" />
        <label className="form-lbl">{t.note}</label>
        <textarea className="form-ta" value={f.note} onChange={function (e) { set('note', e.target.value); }}
                  placeholder={lang === 'fr' ? 'Commentaire…' : 'Comment…'} />
        <div className="form-btns">
          <button className="btn-p" onClick={submit}>{editing ? t.save : t.add}</button>
          <button className="btn-s" onClick={onCancel}>{t.cancel}</button>
        </div>
      </div>
    </div>
  );
}

/* ---- Category Form ---- */
function CategoryForm({ open, lang, onSave, onCancel, usedColors }) {
  var t = UI_TEXT[lang];
  var COLORS = ['#dc2626','#ea580c','#f59e0b','#16a34a','#0d9488','#06b6d4','#3b82f6','#6366f1','#8b5cf6','#a855f7','#db2777','#f43f5e','#78716c','#475569'];
  var avail = COLORS.filter(function (c) { return usedColors.indexOf(c) === -1; });
  var [fr, setFr] = useState('');
  var [en, setEn] = useState('');
  var [color, setColor] = useState(avail[0] || COLORS[0]);

  useEffect(function () {
    if (open) { setFr(''); setEn(''); setColor(avail[0] || COLORS[0]); }
  }, [open]);

  var submit = function () {
    if (!fr.trim()) return;
    onSave({
      id: fr.trim().toLowerCase().replace(/\s+/g, '-').normalize('NFD').replace(/[\u0300-\u036f]/g, ''),
      fr: fr.trim(),
      en: en.trim() || fr.trim(),
      color: color,
      icon: 'pin'
    });
  };

  return (
    <div className={'form-ov' + (open ? ' open' : '')}
         onClick={function (e) { if (e.target === e.currentTarget) onCancel(); }}>
      <div className="form-sheet">
        <div className="form-title">{t.newCat}</div>
        <label className="form-lbl">{t.catNameFr}</label>
        <input className="form-in" value={fr} onChange={function (e) { setFr(e.target.value); }} placeholder="Boucherie" />
        <label className="form-lbl">{t.catNameEn}</label>
        <input className="form-in" value={en} onChange={function (e) { setEn(e.target.value); }} placeholder="Butcher" />
        <label className="form-lbl">{t.color}</label>
        <div className="swatches">
          {COLORS.map(function (c) {
            return <button key={c} className={'swatch' + (color === c ? ' on' : '')}
                          style={{ background: c }} onClick={function () { setColor(c); }} />;
          })}
        </div>
        <div className="form-btns">
          <button className="btn-p" onClick={submit}>{t.add}</button>
          <button className="btn-s" onClick={onCancel}>{t.cancel}</button>
        </div>
      </div>
    </div>
  );
}

/* ---- Device Detection Hook ---- */
function useDevice() {
  function detect() {
    var w = window.innerWidth;
    if (w < 640) return 'phone';
    if (w < 1024) return 'tablet';
    return 'desktop';
  }
  var [device, setDevice] = useState(detect);

  useEffect(function () {
    var onResize = function () {
      var d = detect();
      setDevice(function (prev) { return prev !== d ? d : prev; });
    };
    window.addEventListener('resize', onResize);
    return function () { window.removeEventListener('resize', onResize); };
  }, []);

  return device;
}

var DEVICE_ICONS = {
  phone: function () {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{width:14,height:14}}>
        <rect x="5" y="2" width="14" height="20" rx="2" ry="2"/><line x1="12" y1="18" x2="12.01" y2="18"/>
      </svg>
    );
  },
  tablet: function () {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{width:14,height:14}}>
        <rect x="4" y="2" width="16" height="20" rx="2" ry="2"/><line x1="12" y1="18" x2="12.01" y2="18"/>
      </svg>
    );
  },
  desktop: function () {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{width:14,height:14}}>
        <rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/>
      </svg>
    );
  }
};

function DeviceBadge({ device, lang }) {
  var labels = {
    phone:   { fr: 'Téléphone', en: 'Phone' },
    tablet:  { fr: 'Tablette',  en: 'Tablet' },
    desktop: { fr: 'Bureau',    en: 'Desktop' }
  };
  var Icon = DEVICE_ICONS[device];
  return (
    <div className="device-badge" title={labels[device][lang]}>
      <Icon />
      <span className="device-label">{labels[device][lang]}</span>
    </div>
  );
}

Object.assign(window, { CatIcon, CAT_ICONS, CheckIcon, LangToggle, FilterBar, PlaceCard, PlaceForm, CategoryForm, useDevice, DeviceBadge, OpenBadge, SortToggle });
