// PamojaField.jsx — the Pamoja Field app shell.
//
// Layer 2 of the architecture. Methodology-blind. Reads the METHODOLOGIES
// registry from Workspace.jsx and dispatches to whichever methodology
// workspace the field agent picked (e.g. Cookstoves today, with more
// methodologies plugging in later).
//
// Responsibilities:
//   - own methodology selection state in localStorage
//   - render the first-launch picker until a methodology is chosen
//   - render the active methodology's workspace component
//   - expose a floating switcher button so the agent can swap mid-shift
//
// The shell never imports from a methodology workspace; it only knows
// the registry. To add a new methodology: register it in Workspace.jsx
// with its appKey, and ship the matching workspace JSX exposing that
// app component on window. No edits to this file.

const STORAGE_KEY = 'pamoja_field_workspace';

function PamojaField() {
  const [methodologyId, setMethodologyId] = React.useState(() => {
    try { return localStorage.getItem(STORAGE_KEY) || null; } catch (e) { return null; }
  });
  const [switcherOpen, setSwitcherOpen] = React.useState(false);

  const pick = (id, remember) => {
    setMethodologyId(id);
    try {
      if (remember === false) localStorage.removeItem(STORAGE_KEY);
      else localStorage.setItem(STORAGE_KEY, id);
    } catch (e) {}
    setSwitcherOpen(false);
  };

  // First-launch / cleared selection → show the picker full-bleed.
  if (!methodologyId) {
    return <MethodologyPicker onPick={(id, remember) => pick(id, remember)} />;
  }

  const methodology = methodologyById(methodologyId);
  const ActiveApp = window[methodology.appKey];

  // Defensive: if the methodology's app component isn't loaded yet
  // (script-load order issue), show a minimal fallback rather than crash.
  if (typeof ActiveApp !== 'function') {
    return (
      <div style={{padding:'24px',color:'#022C28',fontFamily:"'Satoshi', system-ui, sans-serif"}}>
        <div style={{fontSize:13,fontWeight:700,color:'#DC2626'}}>Workspace component not loaded</div>
        <div style={{fontSize:12,color:'#6B7280',marginTop:6}}>Expected <code>window.{methodology.appKey}</code> from {methodology.name}.</div>
      </div>
    );
  }

  return (
    <div style={{position:'relative',height:'100%',width:'100%',display:'flex',flexDirection:'column'}}>
      <ActiveApp />

      {/* Floating methodology-switcher button — bottom-right, above the workspace's bottom nav */}
      <button
        onClick={() => setSwitcherOpen(true)}
        aria-label="Switch your work"
        title={`Currently: ${methodology.name} · tap to switch`}
        style={{
          position:'absolute',
          bottom:84,
          right:14,
          zIndex:50,
          display:'flex',
          alignItems:'center',
          gap:6,
          padding:'8px 11px 8px 8px',
          background:'#fff',
          color:'#022C28',
          border:`1.5px solid ${methodology.border}`,
          borderRadius:999,
          cursor:'pointer',
          fontFamily:'inherit',
          boxShadow:'0 6px 18px rgba(2,44,40,0.18)',
        }}
      >
        <span style={{
          width:22,height:22,borderRadius:'50%',
          background: methodology.accent,
          color:'#fff',
          display:'flex',alignItems:'center',justifyContent:'center',
        }}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d={methodology.iconPath}/></svg>
        </span>
        <span style={{fontSize:10,fontWeight:800,letterSpacing:'0.08em',color: methodology.accent,fontFamily:"'JetBrains Mono', monospace",textTransform:'uppercase'}}>{methodology.name}</span>
        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#6B7280" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
      </button>

      <MethodologySwitcher
        open={switcherOpen}
        current={methodologyId}
        onClose={() => setSwitcherOpen(false)}
        onPick={(id) => pick(id, true)}
      />
    </div>
  );
}

window.PamojaField = PamojaField;
