/* ============================================================
   LOCATION LIBRARY — scouting, photos, permits & contacts
   A card per location moving from scouting → hold → locked, with
   reference photos (image-slots), site contact, permit status and
   the shoot day(s) it serves. Rolls up locked locations. Persisted.
   ============================================================ */

const LOCLIB_KEY = 'silverlines.loclib.' + (window.PROJ_ID || 'crimson') + '.v1';

const LOC_STATUS = {
  scouting: { label:'Scouting', tone:'neutral',  icon:'Binoculars' },
  hold:     { label:'On hold',  tone:'amber',    icon:'Clock' },
  locked:   { label:'Locked',   tone:'mint',     icon:'Lock' },
  dropped:  { label:'Dropped',  tone:'neutral',  icon:'CircleSlash' },
};
const LOC_STATUS_ORDER = ['scouting', 'hold', 'locked', 'dropped'];
const PERMIT = {
  none:    { label:'No permit', tone:'neutral', icon:'FileX' },
  applied: { label:'Applied',   tone:'amber',   icon:'FileClock' },
  granted: { label:'Permitted', tone:'mint',    icon:'FileCheck' },
};
const PERMIT_ORDER = ['none', 'applied', 'granted'];

const LOCLIB_SEED = [
  { id:'l1', name:'Hangar 7 — Private Aviation', type:'INT/EXT · Hangar', address:'Van Nuys Airfield, Gate C', status:'locked', permit:'granted', contact:'Ops · Diane Holt', phone:'+1 818 555 0142', days:'Day 1–2', notes:'Power on site. Crane access via north door.' },
  { id:'l2', name:'Runway 19 — Tarmac', type:'EXT · Airfield', address:'Van Nuys Airfield, Apron 4', status:'hold', permit:'applied', contact:'Airfield Mgr · R. Suzuki', phone:'+1 818 555 0190', days:'Day 2', notes:'Golden-hour window only. FAA notice filed.' },
  { id:'l3', name:'Backlot Sky Tank', type:'EXT · Backlot', address:'Stage Lot, Tank 3', status:'scouting', permit:'none', contact:'Lot Booking', phone:'+1 310 555 0118', days:'Day 3', notes:'Recce booked Thu. Confirm bluescreen rig.' },
  { id:'l4', name:'Cockpit Build — Stage 4', type:'INT · Stage', address:'Stage 4, Build Bay', status:'locked', permit:'granted', contact:'Stage Mgr · K. Owens', phone:'+1 310 555 0133', days:'Day 1, 4', notes:'Art dept build in progress. Greenbeds reserved.' },
];

function loclibLoad() {
  const s = window.SLStore.get(LOCLIB_KEY); if (Array.isArray(s) && s.length) return s;
  return window.PROJ_BLANK ? [] : LOCLIB_SEED;
}

function LocLibCard({ l, onPatch, onStatus, onPermit, onRemove, mobile, readOnly }) {
  const st = LOC_STATUS[l.status] || LOC_STATUS.scouting;
  const pm = PERMIT[l.permit] || PERMIT.none;
  return (
    <div className="group/lc overflow-hidden rounded-2xl border border-line bg-ink-850">
      <div className={cx('relative w-full bg-ink-800', mobile ? 'h-[150px]' : 'h-[170px]')}>
        <div className="absolute inset-0 grid grid-cols-2 gap-px">
          <image-slot id={`loc-${l.id}-a`} placeholder={l.name} shape="rect" style={{ width:'100%', height:'100%', color:'rgba(255,255,255,.4)' }}></image-slot>
          <div className="grid grid-rows-2 gap-px">
            <image-slot id={`loc-${l.id}-b`} placeholder="Angle 2" shape="rect" style={{ width:'100%', height:'100%', color:'rgba(255,255,255,.35)' }}></image-slot>
            <image-slot id={`loc-${l.id}-c`} placeholder="Angle 3" shape="rect" style={{ width:'100%', height:'100%', color:'rgba(255,255,255,.35)' }}></image-slot>
          </div>
        </div>
        <button onClick={() => !readOnly && onStatus()} disabled={readOnly} title="Advance status"
          className="absolute left-2 top-2"><Chip tone={st.tone}><Icon name={st.icon} size={11} />{st.label}</Chip></button>
        {!readOnly && (
          <button onClick={onRemove} title="Remove location"
            className="absolute right-2 top-2 flex h-6 w-6 items-center justify-center rounded-md bg-black/60 text-zinc-300 opacity-0 backdrop-blur-sm transition-opacity hover:text-[#FF6B6B] group-hover/lc:opacity-100"><Icon name="Trash2" size={12} /></button>
        )}
      </div>
      <div className="space-y-2 p-3">
        <div>
          <div className="text-[14px] font-700 text-zinc-100"><Edit value={l.name} onChange={v => onPatch({ name: v })} className="text-[14px] font-700" /></div>
          <div className="flex items-center gap-1 text-[11px] text-zinc-500"><Icon name="Tag" size={10} /><Edit value={l.type} onChange={v => onPatch({ type: v })} className="text-[11px]" /></div>
        </div>
        {readOnly
          ? <div className="flex items-start gap-1.5 text-[11.5px] text-zinc-400"><Icon name="MapPin" size={12} className="mt-0.5 shrink-0 text-zinc-600" /><span>{l.address || '—'}</span></div>
          : <window.LocationPicker address={l.address} lat={l.lat} lng={l.lng} compact
              onSet={g => onPatch(g.lat != null ? { address: g.address, lat: g.lat, lng: g.lng } : { address: g.address, lat: null, lng: null })} />}
        <div className="flex flex-wrap items-center gap-2">
          <button onClick={() => !readOnly && onPermit()} disabled={readOnly} title="Cycle permit status"><Chip tone={pm.tone}><Icon name={pm.icon} size={11} />{pm.label}</Chip></button>
          <span className="inline-flex items-center gap-1 rounded-full border border-line bg-ink-900 px-2 py-0.5 text-[10.5px] font-600 text-zinc-400"><Icon name="CalendarDays" size={10} /><Edit value={l.days} onChange={v => onPatch({ days: v })} className="text-[10.5px]" /></span>
        </div>
        <div className="flex items-center justify-between gap-2 border-t border-line pt-2 text-[11.5px]">
          <div className="min-w-0">
            <div className="truncate font-600 text-zinc-300"><Edit value={l.contact} onChange={v => onPatch({ contact: v })} className="text-[11.5px] font-600" /></div>
            <a href={`tel:${(l.phone || '').replace(/\s/g, '')}`} className="font-mono text-[11px] text-zinc-500 hover:text-electric-soft">{l.phone}</a>
          </div>
          <a href={`tel:${(l.phone || '').replace(/\s/g, '')}`} className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-ink-700 text-zinc-400 transition-colors hover:bg-cta hover:text-cta-ink"><Icon name="Phone" size={14} /></a>
        </div>
        <div className="text-[11.5px] text-zinc-500"><Edit value={l.notes} onChange={v => onPatch({ notes: v })} placeholder="Recce notes…" multiline className="text-[11.5px]" /></div>
      </div>
    </div>
  );
}

function LocationModule({ mobile, readOnly = false }) {
  const [locs, setLocsState] = useState(loclibLoad);
  const setLocs = next => setLocsState(prev => {
    const v = typeof next === 'function' ? next(prev) : next;
    window.SLStore.set(LOCLIB_KEY, v);
    return v;
  });

  const locked = locs.filter(l => l.status === 'locked').length;
  const permitted = locs.filter(l => l.permit === 'granted').length;

  const patch = (id, p) => setLocs(ls => ls.map(l => l.id === id ? { ...l, ...p } : l));
  const cycleStatus = id => setLocs(ls => ls.map(l => l.id !== id ? l : { ...l, status: LOC_STATUS_ORDER[(LOC_STATUS_ORDER.indexOf(l.status) + 1) % LOC_STATUS_ORDER.length] }));
  const cyclePermit = id => setLocs(ls => ls.map(l => l.id !== id ? l : { ...l, permit: PERMIT_ORDER[(PERMIT_ORDER.indexOf(l.permit) + 1) % PERMIT_ORDER.length] }));
  const remove = id => {
    const prev = locs; const loc = locs.find(l => l.id === id) || {};
    setLocs(ls => ls.filter(l => l.id !== id));
    window.pushUndo && window.pushUndo(`Removed "${loc.name || 'location'}"`, () => setLocs(prev));
  };
  const add = () => setLocs(ls => [...ls, { id:'l' + Date.now(), name:'New location', type:'INT/EXT', address:'', status:'scouting', permit:'none', contact:'', phone:'', days:'TBD', notes:'' }]);

  return (
    <div className="fade-up">
      {!readOnly && <SectionTitle kicker="Crew & departments · Locations" icon="MapPinned" title="Location Library"
        action={<div className="flex items-center gap-2.5">
          <Chip tone="mint"><Icon name="Lock" size={12} /> {locked}/{locs.length} locked</Chip>
          <Chip tone="neutral"><Icon name="FileCheck" size={12} /> {permitted} permitted</Chip>
          {!readOnly && <button onClick={add} className="flex items-center gap-2 rounded-xl bg-cta px-3.5 py-2.5 text-[12.5px] font-700 text-cta-ink transition-colors hover:bg-cta-hover"><Icon name="Plus" size={15} /> Add location</button>}
        </div>} />}

      {locs.length === 0 ? (
        <EmptyState icon="MapPinned" title="No locations yet"
          sub="Add a location as scouting starts — reference photos, permits and site contacts all live on the card."
          action={!readOnly && <button onClick={add} className="flex items-center gap-2 rounded-xl bg-cta px-3.5 py-2.5 text-[12.5px] font-700 text-cta-ink transition-colors hover:bg-cta-hover"><Icon name="Plus" size={15} /> Add location</button>} />
      ) : (
      <div className={cx('grid gap-4', mobile ? 'grid-cols-1' : 'grid-cols-2 xl:grid-cols-3')}>
        {locs.map(l => (
          <LocLibCard key={l.id} l={l} mobile={mobile} readOnly={readOnly}
            onPatch={p => patch(l.id, p)} onStatus={() => cycleStatus(l.id)} onPermit={() => cyclePermit(l.id)} onRemove={() => remove(l.id)} />
        ))}
      </div>
      )}
    </div>
  );
}

window.LocationModule = LocationModule;
window.loclibLoad = loclibLoad;
