/* eslint-disable */
;(function(){
// יפן 2026 — editing demo: view→edit affordances + all six EditSheet editors.
const DSe = window.Ds2026DesignSystem_dc290c;
const { EditSheet, TextField, ToggleField, ChipSelect, TimeField,
        EditButton, AddButton, ReorderHandle } = DSe;
const { useState, useRef } = React;

const CITY_OPTS = [
  {value:'tokyo', label:'טוקיו',  color:'var(--city-tokyo)',  tint:'var(--city-tokyo-tint)',  deep:'var(--city-tokyo-deep)'},
  {value:'hakone',label:'האקונה', color:'var(--city-hakone)', tint:'var(--city-hakone-tint)', deep:'var(--city-hakone-deep)'},
  {value:'kyoto', label:'קיוטו',  color:'var(--city-kyoto)',  tint:'var(--city-kyoto-tint)',  deep:'var(--city-kyoto-deep)'},
  {value:'osaka', label:'אוסקה',  color:'var(--city-osaka)',  tint:'var(--city-osaka-tint)',  deep:'var(--city-osaka-deep)'},
];
const CAT_OPTS = ['מסעדה','בית קפה','מאפייה','מקדש','סדנה','תצפית','טבע','אתר'].map(v=>({value:v,label:v}));
const VEGAN_OPTS = [
  {value:'full',   label:'100% טבעוני', color:'var(--vegan-full)',    tint:'var(--vegan-full-tint)',    deep:'var(--vegan-full)'},
  {value:'partial',label:'חלקי',        color:'var(--vegan-partial)', tint:'var(--vegan-partial-tint)', deep:'var(--vegan-partial)'},
  {value:'none',   label:'לא אוכל',      color:'var(--vegan-none)',    tint:'var(--vegan-none-tint)',    deep:'var(--vegan-none)'},
];
const CHIP_OPTS = [{value:'cash',label:'מזומן בלבד'},{value:'closed',label:'סגור היום'},{value:'booking',label:'דרושה הזמנה'}];

/* Wire an editor's local form state `s` to the persistence seam. Save passes
   the full row (incl. any fields spread from `init` — id, updated_at, extras)
   to onSave; delete passes init.id. All props optional so the editors.html
   demo (onClose only) still works — save/delete then just close. */
function useSheet({ init, onClose, onSave, onDelete }, s) {
  const save = () => { if (onSave) onSave(s); if (onClose) onClose(); };
  const del  = () => { if (onDelete) onDelete(init.id); if (onClose) onClose(); };
  return { onSave: save, onCancel: onClose, onDelete: init && init.id ? del : undefined };
}

/* ---------- The six editors ---------- */
function PlaceEditor(props) {
  const { init={}, onClose } = props;
  const [s,set]=useState({name:'', cat:'מסעדה', city:'tokyo', vegan:'full', hours:'', chips:[], note:'', ...init});
  const u=(k)=>(v)=>set(o=>({...o,[k]:v}));
  return (
    <EditSheet title="עריכת מקום" accent="var(--city-tokyo)" {...useSheet(props, s)}>
      <TextField label="שם המקום" value={s.name} onChange={u('name')} dir="ltr" hint="לטינית / יפנית" />
      <ChipSelect label="קטגוריה" options={CAT_OPTS} value={s.cat} onChange={u('cat')} />
      <ChipSelect label="עיר" options={CITY_OPTS} value={s.city} onChange={u('city')} />
      <ChipSelect label="סטטוס טבעוני" options={VEGAN_OPTS} value={s.vegan} onChange={u('vegan')} />
      <TimeField label="שעות פתיחה" value={s.hours} onChange={u('hours')} />
      <ChipSelect label="תגיות" multi options={CHIP_OPTS} value={s.chips} onChange={u('chips')} />
      <TextField label="הערה אישית" value={s.note} onChange={u('note')} multiline />
    </EditSheet>
  );
}
function ActivityEditor(props) {
  const { init={}, onClose } = props;
  const [s,set]=useState({time:'', label:'', place:'', cat:'סדנה', vegan:'none', chips:[], ...init});
  const u=(k)=>(v)=>set(o=>({...o,[k]:v}));
  return (
    <EditSheet title="עריכת פעילות" accent="var(--city-kyoto)" {...useSheet(props, s)}>
      <TimeField label="שעה" value={s.time} onChange={u('time')} />
      <TextField label="מה עושים" value={s.label} onChange={u('label')} />
      <TextField label="שם המקום (במקור)" value={s.place} onChange={u('place')} dir="ltr" hint="לטינית / יפנית" />
      <ChipSelect label="קטגוריה" options={CAT_OPTS} value={s.cat} onChange={u('cat')} />
      <ChipSelect label="סטטוס טבעוני" options={VEGAN_OPTS} value={s.vegan} onChange={u('vegan')} />
      <ChipSelect label="תגיות" multi options={CHIP_OPTS} value={s.chips} onChange={u('chips')} />
    </EditSheet>
  );
}
function HotelEditor(props) {
  const { init={}, onClose } = props;
  const [s,set]=useState({name:'', city:'kyoto', inD:'', outD:'', addr:'', postal:'', ...init});
  const u=(k)=>(v)=>set(o=>({...o,[k]:v}));
  return (
    <EditSheet title="עריכת מלון" accent="var(--city-kyoto)" {...useSheet(props, s)}>
      <TextField label="שם המלון" value={s.name} onChange={u('name')} />
      <ChipSelect label="עיר" options={CITY_OPTS} value={s.city} onChange={u('city')} />
      <div style={{display:'flex',gap:12}}>
        <TextField label="צ׳ק-אין" value={s.inD} onChange={u('inD')} style={{flex:1}} />
        <TextField label="צ׳ק-אאוט" value={s.outD} onChange={u('outD')} style={{flex:1}} />
      </div>
      <TextField label="כתובת ביפנית" value={s.addr} onChange={u('addr')} dir="ltr" hint="מוצג לנהג המונית" />
      <TextField label="מיקוד 〒" value={s.postal} onChange={u('postal')} dir="ltr" />
    </EditSheet>
  );
}
// Transfer/ticket forms are FLAT (from/to are plain strings). The store rows
// nest from/to as {code,city}; the screen's save handler maps between them.
function TransferEditor(props) {
  const { init={}, onClose } = props;
  const [s,set]=useState({line:'', from:'', to:'', date:'', time:'', ...init});
  const u=(k)=>(v)=>set(o=>({...o,[k]:v}));
  return (
    <EditSheet title="עריכת מעבר" accent="var(--city-hakone)" {...useSheet(props, s)}>
      <TextField label="קו / שירות" value={s.line} onChange={u('line')} />
      <div style={{display:'flex',gap:12}}>
        <TextField label="מ־" value={s.from} onChange={u('from')} style={{flex:1}} />
        <TextField label="אל" value={s.to} onChange={u('to')} style={{flex:1}} />
      </div>
      <TextField label="תאריך" value={s.date} onChange={u('date')} />
      <TimeField label="שעה" value={s.time} onChange={u('time')} />
    </EditSheet>
  );
}
function TicketEditor(props) {
  const { init={}, onClose } = props;
  const [s,set]=useState({kind:'flight', from:'', to:'', date:'', time:'', code:'', seat:'', ...init});
  const u=(k)=>(v)=>set(o=>({...o,[k]:v}));
  return (
    <EditSheet title="עריכת כרטיס" accent="var(--sky-blue)" {...useSheet(props, s)}>
      <ChipSelect label="סוג" value={s.kind} onChange={u('kind')}
        options={[{value:'flight',label:'✈️ טיסה'},{value:'train',label:'🚄 רכבת'}]} />
      <div style={{display:'flex',gap:12}}>
        <TextField label="מ־" value={s.from} onChange={u('from')} dir="ltr" style={{flex:1}} />
        <TextField label="אל" value={s.to} onChange={u('to')} dir="ltr" style={{flex:1}} />
      </div>
      <TextField label="תאריך" value={s.date} onChange={u('date')} dir="ltr" />
      <TimeField label="שעה" value={s.time} onChange={u('time')} />
      <div style={{display:'flex',gap:12}}>
        <TextField label="קוד הזמנה" value={s.code} onChange={u('code')} dir="ltr" style={{flex:1}} />
        <TextField label="מושב" value={s.seat} onChange={u('seat')} dir="ltr" style={{flex:1}} />
      </div>
    </EditSheet>
  );
}
function NoteEditor(props) {
  const { init={}, onClose } = props;
  const [s,set]=useState({text:'', packed:false, ...init});
  const u=(k)=>(v)=>set(o=>({...o,[k]:v}));
  return (
    <EditSheet title="פריט לרשימה" accent="var(--sun-yellow)" {...useSheet(props, s)}>
      <TextField label="מה לוקחים" value={s.text} onChange={u('text')} />
      <ToggleField label="כבר ארוז" checked={s.packed} onChange={u('packed')} />
    </EditSheet>
  );
}

const EDITORS = { place:PlaceEditor, activity:ActivityEditor, hotel:HotelEditor, transfer:TransferEditor, ticket:TicketEditor, note:NoteEditor };

/* Reusable modal wrapper: dim backdrop + bottom-anchored sheet + tap-outside to
   cancel. Screens render <EditSheetOverlay type onClose ...editorProps/>. Back
   rule: edit sheets use their own ביטול/שמירה + tap-outside (not a TopBar). */
function EditSheetOverlay({ type, onClose, ...editorProps }) {
  const Editor = EDITORS[type];
  if (!Editor) return null;
  return (
    <div onClick={onClose} className="jp-sheet-scrim"
      style={{ position:'absolute', inset:0, zIndex:50, background:'rgba(74,64,58,.34)' }}>
      <div className="jp-sheet-panel" style={{ position:'absolute', insetInline:0, bottom:0 }} onClick={e=>e.stopPropagation()}>
        <Editor onClose={onClose} {...editorProps} />
      </div>
    </div>
  );
}

/* ---------- Edit-mode day timeline with reorder ---------- */
function EditableDay({ onEditActivity, onAddActivity }) {
  const [acts,setActs]=useState([
    {time:'09:30', label:'קפה בוקר',        place:'Silver Backs Cafe'},
    {time:'12:30', label:'סדנת מקלות אכילה', place:'Gion Chopsticks Workshop'},
    {time:'14:15', label:'צהריים טבעוני',    place:'cafe vegan terrace'},
    {time:'19:30', label:'ארוחת ערב',        place:'Vegan Ramen UZU'},
  ]);
  const drag=useRef(null);
  const onDown=(i)=>(e)=>{ drag.current={i, y:e.clientY}; e.target.setPointerCapture?.(e.pointerId); };
  const onMove=(e)=>{ const d=drag.current; if(!d) return; const dy=e.clientY-d.y;
    if(Math.abs(dy)>60){ const j=d.i+(dy>0?1:-1); if(j>=0&&j<acts.length){ setActs(a=>{const n=a.slice();[n[d.i],n[j]]=[n[j],n[d.i]];return n;}); drag.current={i:j,y:e.clientY}; } } };
  const onUp=()=>{ drag.current=null; };
  return (
    <div>
      <div style={{display:'flex',flexDirection:'column',gap:10}} onPointerMove={onMove} onPointerUp={onUp}>
        {acts.map((a,i)=>(
          <div key={a.label} style={{display:'flex',alignItems:'center',gap:10,background:'var(--surface-card)',
            border:'var(--border-card)',borderRadius:'var(--r-md)',padding:'11px 12px',boxShadow:'var(--shadow-sm)'}}>
            <ReorderHandle onPointerDown={onDown(i)} />
            <span className="time-range" style={{fontFamily:'var(--font-ui)',fontSize:13,color:'var(--ink-700)',flex:'0 0 42px'}}>{a.time}</span>
            <span style={{flex:1,minWidth:0}}>
              <span style={{display:'block',fontFamily:'var(--font-ui)',fontSize:15,color:'var(--ink-900)'}}>{a.label}</span>
              <span className="ltr" style={{display:'block',fontSize:12,color:'var(--ink-500)'}}>{a.place}</span>
            </span>
            <EditButton onClick={()=>onEditActivity(a)} />
          </div>
        ))}
      </div>
      <div style={{marginTop:12}}>
        <AddButton label="הוספת פעילות" variant="row" accent="var(--city-kyoto)" onClick={onAddActivity} />
      </div>
    </div>
  );
}

function EditorsScreen() {
  const [sheet,setSheet]=useState(null); // {type}
  return (
    <div style={{ paddingBottom:24 }}>
      <header style={{ padding:'16px 20px 8px' }}>
        <div style={{ fontFamily:'var(--font-ui)', fontSize:13, color:'var(--ink-500)' }}>מצב עריכה ✏️</div>
        <h1 style={{ fontFamily:'var(--font-display)', fontSize:44, lineHeight:0.9, color:'var(--ink-900)', margin:'2px 0 0' }}>יום 11 · קיוטו</h1>
        <div style={{ fontFamily:'var(--font-ui)', fontSize:13, color:'var(--ink-500)', marginTop:2 }}>גררו לשינוי סדר · ✏️ לעריכה · ＋ להוספה</div>
      </header>

      <div style={{ padding:'8px 20px 0' }}>
        <EditableDay onEditActivity={()=>setSheet({type:'activity'})} onAddActivity={()=>setSheet({type:'activity'})} />
      </div>

      <h2 style={{ fontFamily:'var(--font-display)', fontSize:26, color:'var(--ink-700)', margin:'22px 20px 10px', letterSpacing:0.5 }}>כל העורכים 📝</h2>
      <div style={{ display:'flex', flexWrap:'wrap', gap:10, padding:'0 20px' }}>
        {[['place','🍜 מקום'],['activity','🗓️ פעילות'],['hotel','🛏️ מלון'],['transfer','🚄 מעבר'],['ticket','🎫 כרטיס'],['note','🎒 פריט אריזה']].map(([t,l])=>(
          <button key={t} type="button" onClick={()=>setSheet({type:t})}
            style={{ appearance:'none', cursor:'pointer', fontFamily:'var(--font-ui)', fontSize:14, padding:'10px 16px',
              borderRadius:'var(--r-pill)', border:'1.5px solid var(--hairline)', background:'var(--surface-card)', color:'var(--ink-800,var(--ink-900))' }}>{l}</button>
        ))}
      </div>

      {sheet && <EditSheetOverlay type={sheet.type} onClose={()=>setSheet(null)} />}
    </div>
  );
}

window.JP2026Editors = EditorsScreen;
// Editor kit — the six editors + the reusable overlay, for screens to mount.
window.JP2026EditorKit = { EDITORS, EditSheetOverlay };

})();
