// Journey Mapping . App shell
const J_STORAGE_KEY = 'ms_journey_v1';

function useJourneyState() {
  const [data, setData] = React.useState(() => {
    try {
      const saved = localStorage.getItem(J_STORAGE_KEY);
      if (saved) {
        const p = JSON.parse(saved);
        // Migrate old stage IDs (discover/activate/transact) → A-CAR (attract/convert/adopt/retain)
        const oldKeys = ['discover','activate','transact'];
        const hasOld = p.stages && p.stages.some(s => oldKeys.includes(s.id));
        if (hasOld) {
          const map = { discover:'attract', activate:'convert', transact:'adopt', retain:'retain' };
          p.stages = JOURNEY_EXAMPLE.stages;
          for (const side of ['buyer','supplier']) {
            const next = {};
            for (const k of Object.keys(p[side]||{})) {
              next[map[k] || k] = p[side][k];
            }
            p[side] = next;
          }
        }
        return p;
      }
    } catch(e) {}
    return JSON.parse(JSON.stringify(JOURNEY_EXAMPLE));
  });
  React.useEffect(() => {
    try { localStorage.setItem(J_STORAGE_KEY, JSON.stringify(data)); } catch(e) {}
  }, [data]);

  const setPath = React.useCallback((path, value) => {
    setData(prev => {
      const next = JSON.parse(JSON.stringify(prev));
      let obj = next;
      for (let i = 0; i < path.length - 1; i++) {
        if (obj[path[i]] === undefined) obj[path[i]] = {};
        obj = obj[path[i]];
      }
      obj[path[path.length - 1]] = value;
      return next;
    });
  }, []);

  return [data, setPath, setData];
}

function JourneyApp() {
  const [data, setPath, setData] = useJourneyState();
  const onPrint = () => window.print();
  const onReset = () => { if(confirm('Reset to the RigShare example?')) setData(JSON.parse(JSON.stringify(JOURNEY_EXAMPLE))); };
  const onClear = () => {
    if(!confirm('Clear all example data?')) return;
    const blank = JSON.parse(JSON.stringify(JOURNEY_EXAMPLE));
    blank.meta = { name:'', category:'', buyerName:'Buyer', supplierName:'Supplier' };
    blank.buyer = {};
    blank.supplier = {};
    blank.stages.forEach(s => {
      blank.buyer[s.id] = { action:'', thinking:'', feeling:'', pain:'', opportunity:'' };
      blank.supplier[s.id] = { action:'', thinking:'', feeling:'', pain:'', opportunity:'' };
    });
    setData(blank);
  };
  const onBook = () => window.open('Marketplace Studio.html', '_blank');

  return (
    <>
      <JourneyTopbar onPrint={onPrint} onReset={onReset} onClear={onClear}/>
      <main className="lm-doc lm-doc-wide">
        <JourneyCover data={data} onChange={setPath}/>
        <JourneyMap data={data} onChange={setPath}/>
        <JourneySynthesis data={data} onBook={onBook}/>
      </main>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('app')).render(<JourneyApp/>);
