// ============================================================
// wf-flows.jsx — IA: user-flow charts + architecture diagrams
// Exports FlowsView and ArchView to window.
// ============================================================

/* =====================  USER FLOWS  ===================== */
function FlowsView(){
  return (
    <React.Fragment>
      <SectionHead
        kicker="Information Architecture · User Flows"
        title="Cross-platform task & decision flows"
        desc="How operators move through the critical paths. Navy pills = entry / state, navy boxes = process steps, amber diamonds = decision points, dashed blue = input / data, teal pills = success end, red = failure end."
      />
      <Row gap={16} wrap style={{marginBottom:22}}>
        <Note><span style={{width:11,height:11,borderRadius:11,background:'var(--navy)',display:'inline-block'}}/> Start / state</Note>
        <Note><span style={{width:11,height:11,background:'var(--navy)',display:'inline-block',borderRadius:2}}/> Process</Note>
        <Note><span style={{width:11,height:11,background:'#fffdf5',border:'1.5px solid var(--warn)',display:'inline-block',transform:'rotate(45deg)'}}/> Decision</Note>
        <Note><span style={{width:11,height:11,borderRadius:11,background:'var(--teal)',display:'inline-block'}}/> Success</Note>
        <Note><span style={{width:11,height:11,borderRadius:11,background:'var(--crit)',display:'inline-block'}}/> Failure</Note>
      </Row>

      {/* AUTH FLOW */}
      <FlowCard tag="All platforms" title="Authentication & Session" caption="Shared identity service. SSO is the primary path; credentials and CAC/PIV are alternates. Mobile adds biometric resume within the 24-hour window. Every platform shows a 2-minute pre-expiry warning.">
        <FNode type="start" title="Launch app"/>
        <FDown/>
        <FDec title="Valid session?"/>
        <FSplit>
          <FLane>
            <FDown label="mobile · yes"/>
            <FNode title="Biometric resume" sub="Face ID / Touch ID"/>
            <FDown/>
            <FNode type="end" title="Enter app"/>
          </FLane>
          <FLane>
            <FDown label="no"/>
            <FNode title="Select organization" sub="routes IdP config"/>
            <FDown/>
            <FDec title="Auth method"/>
            <FSplit gap={20}>
              <FLane><FDown label="SSO"/><FNode type="io" title="SAML 2.0 / OIDC"/></FLane>
              <FLane><FDown label="creds"/><FNode type="io" title="Email + password"/><FDown/><FNode title="MFA" sub="TOTP / FIDO2"/></FLane>
              <FLane><FDown label="CAC/PIV"/><FNode type="io" title="Smart card" sub="if reader present"/></FLane>
            </FSplit>
            <FDown/>
            <FDec title="Verified?"/>
            <FSplit gap={26}>
              <FLane><FDown label="✓"/><FNode type="end" title="Enter app"/></FLane>
              <FLane><FDown label="✗"/><FNode type="end" className="fail" title="Show error + retry"/></FLane>
            </FSplit>
          </FLane>
        </FSplit>
      </FlowCard>

      {/* PAIRING FLOW */}
      <FlowCard tag="Mobile" title="Device Pairing (BLE / USB / Manual)" caption="From Home › Pair New Device or Devices › +. Failure routes to troubleshooting and back to method selection.">
        <FNode type="start" title="Tap “Pair Device”"/>
        <FDown/>
        <FDec title="Connection method"/>
        <FSplit gap={20}>
          <FLane><FDown label="BLE"/><FNode title="Radar scan" sub="discovered list"/></FLane>
          <FLane><FDown label="USB"/><FNode title="Auto-detect"/></FLane>
          <FLane><FDown label="Manual"/><FNode type="io" title="Enter serial"/></FLane>
        </FSplit>
        <FDown/>
        <FNode title="Confirm device" sub="name · serial · type"/>
        <FDown/>
        <FNode title="Handshake + auth" sub="pairing code if required"/>
        <FDown/>
        <FDec title="Paired OK?"/>
        <FSplit gap={26}>
          <FLane><FDown label="✓"/><FNode type="end" title="Added to team"/><FDown/><FNode title="Go to Device"/></FLane>
          <FLane><FDown label="✗"/><FNode type="end" className="fail" title="Failure + tips"/><FDown/><FNode title="Retry" sub="back to method"/></FLane>
        </FSplit>
      </FlowCard>

      {/* CALIBRATION FLOW */}
      <FlowCard tag="Desktop" title="Calibration Workflow" caption="Six-step guided wizard. Pre-checks and each calibration step gate on pass/fail before proceeding; failures can be re-run.">
        <FNode type="start" title="Start Calibration"/>
        <FDown/>
        <FNode title="Select device" sub="connected / auto"/>
        <FDown/>
        <FNode title="Pick profile" sub="org or custom"/>
        <FDown/>
        <FDec title="Pre-checks pass?"/>
        <FSplit gap={26}>
          <FLane><FDown label="no"/><FNode type="end" className="fail" title="Block + remedy"/></FLane>
          <FLane>
            <FDown label="yes"/>
            <FNode title="Run calibration steps" sub="live gauge · waveform · readout"/>
            <FDown/>
            <FDec title="Step passes?"/>
            <FSplit gap={20}>
              <FLane><FDown label="no"/><FNode title="Re-run step"/></FLane>
              <FLane><FDown label="yes"/><FNode title="Review & confirm"/><FDown/><FNode title="Generate certificate" sub="signed PDF → record"/><FDown/><FNode type="end" title="Stored to device"/></FLane>
            </FSplit>
          </FLane>
        </FSplit>
      </FlowCard>

      {/* GESTURE LIFECYCLE */}
      <FlowCard tag="Mobile · Motion Gestures" title="Gesture Lifecycle — Record → Arm → Recognize → Confirm" caption="Recognition is OFF until explicitly armed. Every recognized gesture requires tap-to-confirm; the confirmation modal auto-cancels on timeout (fail-safe, never fail-action). Restricted shortcuts force confirmation on.">
        <FNode type="start" title="Record New Gesture"/>
        <FDown/>
        <FDec title="Device + IMU healthy?"/>
        <FSplit gap={26}>
          <FLane><FDown label="no"/><FNode type="end" className="fail" title="Disabled — reconnect"/></FLane>
          <FLane>
            <FDown label="yes"/>
            <FNode title="Capture motion" sub="live IMU waveform"/>
            <FDown/>
            <FNode title="Review signature"/>
            <FDown/>
            <FNode title="Test recognition" sub="confidence · pass/fail"/>
            <FDown/>
            <FNode title="Name + bind shortcut" sub="confirm-required (locked for restricted)"/>
            <FDown/>
            <FNode type="evt" title="Save + audit event"/>
            <FDown/>
            <FNode type="start" title="ARM recognition" sub="persistent banner shown"/>
            <FDown/>
            <FNode title="IMU stream matched (DTW)"/>
            <FDown/>
            <FDec title="Confidence ≥ threshold?"/>
            <FSplit gap={20}>
              <FLane><FDown label="no"/><FNode title="Ignore" sub="keep listening"/></FLane>
              <FLane>
                <FDown label="yes"/>
                <FNode title="Confirmation modal" sub="haptic + countdown"/>
                <FDown/>
                <FDec title="Confirm before timeout?"/>
                <FSplit gap={20}>
                  <FLane><FDown label="confirm"/><FNode title="Execute shortcut"/><FDown/><FNode type="end" title="Done + audit"/></FLane>
                  <FLane><FDown label="cancel / timeout"/><FNode type="end" className="fail" title="No action"/></FLane>
                </FSplit>
              </FLane>
            </FSplit>
          </FLane>
        </FSplit>
      </FlowCard>

      {/* OFFLINE SYNC */}
      <FlowCard tag="Mobile · Offline-first" title="Connectivity & Sync" caption="The app degrades gracefully across three states. Paired-device interaction over BLE/USB stays functional offline; queued data syncs with conflict resolution on reconnect.">
        <FNode type="start" title="In use"/>
        <FDown/>
        <FDec title="Connectivity?"/>
        <FSplit gap={20}>
          <FLane><FDown label="online"/><FNode title="Full sync" sub="live metrics"/></FLane>
          <FLane><FDown label="degraded"/><FNode type="evt" title="Amber banner" sub="stale timestamps"/><FDown/><FNode title="Background sync"/></FLane>
          <FLane><FDown label="offline"/><FNode type="evt" title="Red banner" sub="cached data"/><FDown/><FNode type="io" title="Queue locally" sub="comms · reports · audit"/></FLane>
        </FSplit>
        <FDown label="on reconnect"/>
        <FNode title="Flush outbox + resolve conflicts"/>
        <FDown/>
        <FNode type="end" title="Synced"/>
      </FlowCard>
    </React.Fragment>
  );
}

/* =====================  ARCHITECTURE  ===================== */
const FEATURES = [
  ['Authentication / Login','✓','✓','✓'],
  ['Dashboard / Home','connected devices','fleet KPIs','my devices'],
  ['Device List','connected only','all org devices','team devices'],
  ['Device Detail','hardware-deep','status + history','real-time + actions'],
  ['Fleet Map','—','✓ primary','mini-map'],
  ['Calibration','✓ primary','view history','—'],
  ['Firmware Mgmt','✓ primary','view + OTA','—'],
  ['Diagnostics','full suites','view results','field diagnostics'],
  ['Configuration','✓ primary','view + push','—'],
  ['Test Suites','✓ primary','view results','—'],
  ['Events / Activity','local','org-wide ✓','my devices'],
  ['Alerts','local','org-wide ✓','my devices'],
  ['Comms / Messaging','—','—','✓ primary'],
  ['Device Pairing','USB / serial','—','BLE/USB ✓'],
  ['Motion Gestures','—','admin templates','✓ primary'],
  ['Field Reports','—','view submitted','create + submit'],
  ['Admin Panel','—','✓ primary','—'],
  ['Reports / Analytics','—','✓ primary','—'],
  ['Settings','✓','✓','✓'],
];
const ROLES = [
  ['Super Admin','Full + org cal profiles','Full + audit','Full + override'],
  ['Org Admin','Full cal & diag','Org + registry','Reassign devices'],
  ['Ops Analyst','View diagnostics','Dashboards / logs','View status'],
  ['HW Technician','Full cal/fw/diag','View health','Pair / field diag'],
  ['Field Operator','No access','View dashboards','Full field access'],
  ['Viewer','View-only','View-only','View-only'],
];
const cellFmt = (v) => v==='✓'||v==='—' ? (v==='✓'?<MxCheck/>:<MxDash/>) :
  v.includes('✓') ? <span><MxCheck/> <MxNote>{v.replace('✓','').trim()}</MxNote></span> : <MxNote>{v}</MxNote>;

function ArchView(){
  return (
    <React.Fragment>
      <SectionHead
        kicker="Information Architecture · System"
        title="Architecture, tenancy & access model"
        desc="The structural backbone shared by all three apps: the org/tenant hierarchy, role-based permissions, the cross-platform feature distribution, and the mobile connectivity model."
      />

      {/* HIERARCHY */}
      <div className="fl-card">
        <div className="fl-tag">Multi-tenant model</div>
        <h4>Organization Hierarchy</h4>
        <p className="cap">Each organization is a fully isolated tenant — no cross-tenant visibility. A device belongs to exactly one Team at a time; transfer requires an admin action.</p>
        <div className="wf-hier">
          <div className="hn">Organization <span style={{opacity:.7,fontWeight:400}}>· e.g. JSOC Task Force Alpha</span></div>
          <div className="hl"/>
          <div className="hrow">
            {['Signals Division','Recon Division'].map((d,i)=><div key={i} className="fl-col"><div className="hn d2">{d}</div></div>)}
          </div>
          <div className="hl"/>
          <div className="hrow">
            {['Team Bravo','Team Alpha','Watch Floor'].map((t,i)=><div key={i} className="hn d3">{t}</div>)}
          </div>
          <div className="hl"/>
          <div className="hrow">
            {['AC-7740','AC-7741','AC-3320','AC-9008'].map((d,i)=><div key={i} className="hn d4">{d}</div>)}
          </div>
        </div>
      </div>

      {/* FEATURE MATRIX */}
      <div className="fl-card">
        <div className="fl-tag">Distribution</div>
        <h4>Cross-Platform Feature Matrix</h4>
        <p className="cap">Which IA sections live on which platform, and the role each plays. Intentional overlap in device data; interaction model and density tuned per context.</p>
        <Box style={{padding:0,overflow:'hidden'}}>
          <Table cols={['Feature / Section','Desktop','Web','Mobile']} rows={FEATURES.map(r=>[<b style={{fontWeight:600}}>{r[0]}</b>,cellFmt(r[1]),cellFmt(r[2]),cellFmt(r[3])])}/>
        </Box>
      </div>

      {/* ROLES MATRIX */}
      <div className="fl-card">
        <div className="fl-tag">Access control</div>
        <h4>Roles &amp; Permissions</h4>
        <p className="cap">One role per user, assigned at the org level. No role inheritance — deliberate, to prevent privilege confusion in classified environments.</p>
        <Box style={{padding:0,overflow:'hidden'}}>
          <Table cols={['Role','Desktop','Web','Mobile']} rows={ROLES.map(r=>[<b style={{fontWeight:600}}>{r[0]}</b>,<MxNote>{r[1]}</MxNote>,<MxNote>{r[2]}</MxNote>,<MxNote>{r[3]}</MxNote>])}/>
        </Box>
      </div>

      {/* AUTH/SESSION + CONNECTIVITY */}
      <div className="arch-grid" style={{gridTemplateColumns:'1fr 1fr'}}>
        <div className="fl-card" style={{marginBottom:0}}>
          <div className="fl-tag">Identity</div>
          <h4>Session Model</h4>
          <Box style={{padding:0,overflow:'hidden',marginTop:6}}>
            <Table cols={['Platform','Duration','Offline']} rows={[
              ['Desktop','8h (idle 30m)','Cached creds; cal queued'],
              ['Web','4h sliding (idle 15m)','Requires connection'],
              ['Mobile','24h + biometric','Cached token; re-auth on reconnect'],
            ].map(r=>[<b style={{fontWeight:600}}>{r[0]}</b>,<MxNote>{r[1]}</MxNote>,<MxNote>{r[2]}</MxNote>])}/>
          </Box>
          <p className="cap" style={{margin:'12px 0 0'}}>All platforms show a 2-minute pre-expiry warning modal with extend / log-out.</p>
        </div>
        <div className="fl-card" style={{marginBottom:0}}>
          <div className="fl-tag">Mobile · offline-first</div>
          <h4>Connectivity States</h4>
          <Col gap={10} style={{marginTop:6}}>
            {[['ok','Online','Full functionality. Real-time sync, live metrics.'],
              ['warn','Degraded','Banner. Stale timestamps. Background sync when bandwidth allows.'],
              ['crit','Offline','Persistent banner. Cached data + staleness. BLE/USB still works. Queue + sync on reconnect.']].map((s,i)=>(
              <div className="arch-state" key={i}><div className="sh"><Dot s={s[0]}/>{s[1]}</div><Label style={{fontSize:11.5,lineHeight:1.5}}>{s[2]}</Label></div>
            ))}
          </Col>
        </div>
      </div>

      <div style={{marginTop:18}}>
        <Note><b>ITAR-by-design</b> — classification banner, audit logging, export-permission checks, and data-classification labels are assumed on every surface, not bolted on.</Note>
      </div>
    </React.Fragment>
  );
}

window.FlowsView = FlowsView;
window.ArchView = ArchView;
