// Interactive navigation flow diagram
// Click a node → highlights its connections. Or click a JOURNEY at top
// to trace a common path through the app.
const { Icon } = window;

function NavDiagram() {
  const T = UN.d;
  const [selected, setSelected] = React.useState(null);
  const [journey, setJourney] = React.useState('signup');

  // Named journeys — sequence of node ids representing common flows
  const journeys = {
    signup: {
      label: 'Sign-up journey',
      color: '#a5b8c9',
      path: ['ob1','ob2','ob3','ob4','ob5','ob6','ob7','ob7b','ob8','ob9','pay','ob10','home'],
    },
    logging: {
      label: 'Logging journey',
      color: UN.d.sage,
      path: ['home','log','dose','tl'],
    },
    handoff: {
      label: 'Doctor handoff',
      color: UN.d.trust,
      path: ['home','ep','doc'],
    },
    invite: {
      label: 'Caregiver invite',
      color: '#d3a89a',
      path: ['home','cg','addcg'],
    },
    close: {
      label: 'Close + retrospective',
      color: UN.d.sev.warm,
      path: ['ep','close','home'],
    },
  };

  const nodes = [
    // ── ONBOARDING ──
    { id: 'ob1',  l: 'Caregiver sync',   icon: 'people',  x:   60, y:  90 },
    { id: 'ob2',  l: 'Voice teaser',     icon: 'mic',     x:  200, y:  90 },
    { id: 'ob3',  l: 'Pediatrician',     icon: 'doc',     x:  340, y:  90 },
    { id: 'ob4',  l: 'Country',          icon: 'gear',    x:  480, y:  90 },
    { id: 'ob5',  l: 'Who are you',      icon: 'people',  x:  620, y:  90 },
    { id: 'ob6',  l: 'Sick now?',        icon: 'thermo',  x:  760, y:  90 },
    { id: 'ob7',  l: 'What with',        icon: 'alert',   x:  900, y:  90 },
    { id: 'ob7b', l: 'Doctor confirmed?', icon: 'check',  x: 1040, y:  90 },
    { id: 'ob8',  l: 'Add child',        icon: 'plus',    x: 1180, y:  90 },
    { id: 'ob9',  l: 'Personalising',    icon: 'clock',   x: 1320, y:  90 },
    { id: 'pay',  l: 'Paywall',          icon: 'gear',    x: 1320, y: 180 },
    { id: 'ob10', l: 'Sign up',          icon: 'check',   x: 1180, y: 180 },

    // ── HOME HUB ──
    { id: 'home',     l: 'HOME',         icon: 'home',    x: 690, y: 290, big: true },
    { id: 'home-s',   l: 'Home scroll',  icon: 'chevDown',x: 540, y: 290 },

    // ── EPISODE ──
    { id: 'ep',       l: 'Episode',      icon: 'thermo',  x: 920, y: 290, big: true },
    { id: 'ep-s',     l: 'Dim selected', icon: 'thermo',  x: 920, y: 390 },
    { id: 'tl',       l: 'Full timeline',icon: 'clock',   x: 1120, y: 290 },
    { id: 'photos',   l: 'Photos',       icon: 'camera',  x: 1120, y: 390 },
    { id: 'edit',     l: 'Edit entry',   icon: 'pill',    x: 1280, y: 290 },

    // ── LOGGING ──
    { id: 'log',      l: '+ Log',        icon: 'plus',    x: 690, y: 470, big: true },
    { id: 'dose',     l: 'Dose',         icon: 'pill',    x: 420, y: 550 },
    { id: 'temp',     l: 'Temp',         icon: 'thermo',  x: 540, y: 550 },
    { id: 'sym',      l: 'Symptom',      icon: 'alert',   x: 660, y: 550 },
    { id: 'obs',      l: 'Observation',  icon: 'mic',     x: 780, y: 550 },
    { id: 'sleep',    l: 'Sleep',        icon: 'clock',   x: 900, y: 550 },
    { id: 'fluid',    l: 'Fluid',        icon: 'drop',    x: 540, y: 630 },
    { id: 'vomit',    l: 'Vomit',        icon: 'vomit',   x: 660, y: 630 },
    { id: 'diaper',   l: 'Urine',        icon: 'diaper',  x: 780, y: 630 },
    { id: 'food',     l: 'Food',         icon: 'food',    x: 900, y: 630 },

    // ── VOICE / WIDGET ──
    { id: 'voice',    l: 'Voice log',    icon: 'mic',     x: 320, y: 290, big: true },
    { id: 'widget',   l: 'Lock widget',  icon: 'home',    x: 160, y: 290 },

    // ── ALERTS ──
    { id: 'push',     l: 'Push',         icon: 'bell',    x: 160, y: 430 },
    { id: 'alert',    l: 'In-app alert', icon: 'alert',   x: 320, y: 430 },
    { id: 'rf',       l: 'Wet diaper',   icon: 'drop',    x: 320, y: 520 },

    // ── CONFIGURE ──
    { id: 'set',      l: 'Settings',     icon: 'gear',    x: 100, y: 740 },
    { id: 'meds',     l: 'Meds',         icon: 'pill',    x: 260, y: 740 },
    { id: 'tpl',      l: 'Templates',    icon: 'alert',   x: 420, y: 740 },
    { id: 'cg',       l: 'Caregivers',   icon: 'people',  x: 580, y: 740 },
    { id: 'addcg',    l: 'Invite',       icon: 'plus',    x: 580, y: 820 },
    { id: 'custom',   l: 'Custom cond.', icon: 'plus',    x: 420, y: 820 },
    { id: 'jrny',     l: 'Journey',      icon: 'pill',    x: 260, y: 820 },

    // ── LIFECYCLE / SHARE ──
    { id: 'start',    l: 'Start episode',icon: 'plus',    x: 1280, y: 470 },
    { id: 'close',    l: 'Close · retro',icon: 'check',   x: 1280, y: 550 },
    { id: 'doc',      l: 'Doctor view',  icon: 'share',   x: 1280, y: 640 },
  ];

  const edges = [
    // Onboarding chain
    ['ob1','ob2','tap'],   ['ob2','ob3','tap'],   ['ob3','ob4','tap'],
    ['ob4','ob5','tap'],   ['ob5','ob6','tap'],
    ['ob6','ob7','yes'],   ['ob6','ob8','no'],
    ['ob7','ob7b','tap'],  ['ob7b','ob8','tap'],
    ['ob8','ob9','tap'],   ['ob9','pay','done'],
    ['pay','ob10','subscribe'],
    ['ob10','home','done'],

    ['home','ep','tap kid'],
    ['home','home-s','scroll'],
    ['home','start','well kid'],
    ['home','cg','avatar'],

    ['ep','tl','swipe'],
    ['ep','ep-s','tap chip'],
    ['tl','photos','tap photo'],
    ['tl','edit','swipe row'],

    ['home','log','+ button'],
    ['ep','log','+ button'],
    ['tl','log','+ button'],
    ['log','dose','tap'],
    ['log','temp','tap'],
    ['log','sym','tap'],
    ['log','obs','tap'],
    ['log','sleep','tap'],
    ['log','fluid','tap'],
    ['log','vomit','tap'],
    ['log','diaper','tap'],
    ['log','food','tap'],

    ['home','voice','top-right'],
    ['ep','voice','top-right'],
    ['tl','voice','top-right'],
    ['voice','widget','from lock'],

    ['push','home','tap'],
    ['alert','rf','tap'],
    ['ep','alert','inline'],
    ['rf','log','log wet'],

    ['home','set','avatar'],
    ['set','meds','tap'],
    ['set','tpl','tap'],
    ['set','cg','tap'],
    ['cg','addcg','+ invite'],
    ['tpl','jrny','select'],
    ['tpl','custom','+ custom'],
    ['start','jrny','pick'],

    ['ep','close','dismiss'],
    ['close','home','done'],
    ['ep','doc','share'],
  ];

  const out = selected ? edges.filter(e => e[0] === selected).map(e => e[1]) : [];
  const inn = selected ? edges.filter(e => e[1] === selected).map(e => e[0]) : [];
  const selHighlighted = new Set([...(selected ? [selected] : []), ...out, ...inn]);
  const selEdges = new Set(edges
    .filter(e => selected && (e[0] === selected || e[1] === selected))
    .map(e => `${e[0]}-${e[1]}`));

  // Journey path edges
  const jp = journeys[journey];
  const jEdges = new Set();
  if (jp) {
    for (let i = 0; i < jp.path.length - 1; i++) {
      jEdges.add(`${jp.path[i]}-${jp.path[i+1]}`);
    }
  }
  const jNodes = new Set(jp?.path || []);

  const nodeMap = Object.fromEntries(nodes.map(n => [n.id, n]));
  const edgePath = (a, b) => {
    const A = nodeMap[a], B = nodeMap[b];
    if (!A || !B) return '';
    const aw = A.big ? 110 : 90;
    const ah = A.big ? 70 : 50;
    const bw = B.big ? 110 : 90;
    const bh = B.big ? 70 : 50;
    const ax = A.x + aw / 2;
    const ay = A.y + ah / 2;
    const bx = B.x + bw / 2;
    const by = B.y + bh / 2;
    const mx = (ax + bx) / 2;
    const my = (ay + by) / 2;
    const cx = ax === bx ? ax + 40 : mx;
    const cy = ay === by ? ay + 40 : my;
    return `M ${ax},${ay} Q ${cx},${cy} ${bx},${by}`;
  };

  return (
    <div style={{
      width: 1500, height: 900, position: 'relative',
      fontFamily: UN.font.body,
      background: T.bg,
      color: T.text, overflow: 'hidden',
    }}>
      {/* Header */}
      <div style={{ position: 'absolute', left: 24, top: 14, right: 24, display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontSize: 10.5, color: T.sage, letterSpacing: 1.6, fontWeight: 700, textTransform: 'uppercase' }}>
            UNPANIC · MAP
          </div>
          <div style={{ marginTop: 2, fontSize: 17, color: T.text, fontWeight: 700, letterSpacing: -0.2 }}>
            Pick a journey to trace it. Click any node for its connections.
          </div>
        </div>
        {/* Journey selector */}
        <div style={{ display: 'flex', gap: 4 }}>
          {Object.entries(journeys).map(([k, j]) => {
            const on = journey === k;
            return (
              <button key={k} onClick={() => { setJourney(k); setSelected(null); }} style={{
                padding: '6px 11px', borderRadius: 99,
                background: on ? j.color : T.surface,
                border: `1.5px solid ${on ? j.color : T.line2}`,
                color: on ? '#0E1A14' : T.textDim,
                fontFamily: UN.font.body, fontSize: 11.5, fontWeight: on ? 700 : 500,
                cursor: 'pointer',
              }}>
                {j.label}
              </button>
            );
          })}
          <button onClick={() => { setJourney(null); setSelected(null); }} style={{
            padding: '6px 9px', borderRadius: 99,
            background: !journey ? T.surface2 : 'transparent', border: `1px solid ${T.line2}`,
            color: T.textMute, fontSize: 11, fontWeight: 600,
            cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', gap: 4,
          }}>
            <Icon name="x" size={10} color={T.textMute} strokeWidth={2.4}/>
            None
          </button>
        </div>
      </div>

      {/* Cluster labels */}
      {[
        { l: 'ONBOARDING', x: 60, y: 64 },
        { l: 'DAILY USE', x: 540, y: 256 },
        { l: 'LOGGING', x: 690 - 60, y: 510 },
        { l: 'VOICE + ALERTS', x: 100, y: 256 },
        { l: 'CONFIGURE', x: 80, y: 716 },
        { l: 'LIFECYCLE', x: 1240, y: 444 },
      ].map((c,i) => (
        <div key={i} style={{
          position: 'absolute', left: c.x, top: c.y,
          fontSize: 10, color: T.sage, letterSpacing: 1, fontWeight: 700,
        }}>{c.l}</div>
      ))}

      {/* SVG edges */}
      <svg width={1500} height={900} style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
        <defs>
          <marker id="arr-dim" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill="#888" opacity="0.5"/>
          </marker>
          <marker id="arr-sel" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill={T.sage}/>
          </marker>
          <marker id="arr-jrny" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
            <path d="M0,0 L10,5 L0,10 z" fill={jp?.color || T.sage}/>
          </marker>
        </defs>
        {edges.map((e, i) => {
          const key = `${e[0]}-${e[1]}`;
          const inJourney = jEdges.has(key);
          const inSelection = selEdges.has(key);
          const isDimmed = (selected && !inSelection) || (journey && !inJourney && !inSelection);
          return (
            <path
              key={i}
              d={edgePath(e[0], e[1])}
              fill="none"
              stroke={inSelection ? T.sage : inJourney ? jp.color : '#9aa0aa'}
              strokeWidth={inSelection ? 2.5 : inJourney ? 2.5 : 1.4}
              opacity={isDimmed ? 0.08 : (inSelection || inJourney) ? 1 : 0.38}
              markerEnd={`url(#${inSelection ? 'arr-sel' : inJourney ? 'arr-jrny' : 'arr-dim'})`}
              strokeDasharray={inSelection || inJourney ? '0' : '3 4'}
            />
          );
        })}
      </svg>

      {/* Nodes */}
      {nodes.map(n => {
        const inSel = selHighlighted.has(n.id);
        const inJrn = jNodes.has(n.id);
        const isSelected = n.id === selected;
        const dimmed = (selected && !inSel) || (journey && !inJrn && !inSel);
        const w = n.big ? 110 : 90;
        const h = n.big ? 70 : 50;
        const accentColor = isSelected ? T.sage : (inJrn && journey) ? jp.color : T.sage;
        return (
          <button
            key={n.id}
            onClick={() => setSelected(s => s === n.id ? null : n.id)}
            style={{
              position: 'absolute', left: n.x, top: n.y, width: w, height: h,
              borderRadius: 12,
              background: isSelected
                ? `linear-gradient(180deg, ${T.sage}, ${T.sageDeep})`
                : (inJrn && journey)
                  ? `${jp.color}28`
                  : T.surface,
              border: `1.5px solid ${isSelected ? T.sage : (inJrn && journey) ? jp.color : T.line2}`,
              padding: n.big ? '8px 8px' : '6px 8px',
              display: 'flex', flexDirection: 'column', alignItems: 'flex-start', justifyContent: 'space-between',
              cursor: 'pointer',
              opacity: dimmed ? 0.25 : 1,
              transition: 'opacity .15s, transform .15s, box-shadow .15s',
              boxShadow: isSelected
                ? `inset 0 1px 0 rgba(255,255,255,0.3), 0 8px 18px rgba(143,181,162,0.5)`
                : (inJrn && journey)
                  ? `0 4px 12px ${jp.color}50`
                  : `0 2px 6px rgba(0,0,0,0.3)`,
              color: isSelected ? '#0E1A14' : T.text,
              fontFamily: UN.font.body,
              transform: isSelected ? 'translateY(-2px)' : 'translateY(0)',
            }}>
            <Icon name={n.icon} size={n.big ? 18 : 14}
                  color={isSelected ? '#0E1A14' : (inJrn && journey) ? jp.color : T.sage}
                  strokeWidth={2}/>
            <div style={{
              fontSize: n.big ? 12 : 10.5,
              fontWeight: n.big ? 700 : 600,
              letterSpacing: -0.1,
              textAlign: 'left', lineHeight: 1.1,
              color: isSelected ? '#0E1A14' : T.text,
            }}>{n.l}</div>
          </button>
        );
      })}

      {/* Selection info card */}
      {selected && (() => {
        const n = nodeMap[selected];
        if (!n) return null;
        const outs  = edges.filter(e => e[0] === selected);
        const inns  = edges.filter(e => e[1] === selected);
        return (
          <div style={{
            position: 'absolute', left: 24, bottom: 24,
            width: 360, padding: '14px 16px', borderRadius: 16,
            background: T.surface, border: `1.5px solid ${T.sageEdge}`,
            boxShadow: '0 16px 40px rgba(0,0,0,0.4)',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
              <div style={{
                width: 30, height: 30, borderRadius: 9,
                background: T.sageSoft, border: `1px solid ${T.sageEdge}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <Icon name={n.icon} size={14} color={T.sage} strokeWidth={2}/>
              </div>
              <div style={{ fontSize: 15, color: T.text, fontWeight: 700, letterSpacing: -0.2 }}>{n.l}</div>
            </div>
            {inns.length > 0 && (
              <>
                <div style={{ fontSize: 10, color: T.textMute, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 4 }}>
                  Reached from
                </div>
                {inns.map((e,i) => (
                  <div key={i} style={{ fontSize: 12, color: T.textDim, marginBottom: 2 }}>
                    ← {nodeMap[e[0]]?.l} <span style={{ color: T.textMute }}>· {e[2]}</span>
                  </div>
                ))}
              </>
            )}
            {outs.length > 0 && (
              <>
                <div style={{ fontSize: 10, color: T.textMute, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase', margin: '8px 0 4px' }}>
                  Leads to
                </div>
                {outs.map((e,i) => (
                  <div key={i} style={{ fontSize: 12, color: T.textDim, marginBottom: 2 }}>
                    → {nodeMap[e[1]]?.l} <span style={{ color: T.sage }}>· {e[2]}</span>
                  </div>
                ))}
              </>
            )}
          </div>
        );
      })()}

      {/* Journey legend in bottom-right when no selection */}
      {!selected && jp && (
        <div style={{
          position: 'absolute', right: 24, bottom: 24,
          padding: '12px 16px', borderRadius: 14,
          background: T.surface, border: `1.5px solid ${jp.color}`,
          boxShadow: '0 12px 30px rgba(0,0,0,0.3)',
          maxWidth: 360,
        }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8,
            fontSize: 11, color: jp.color, letterSpacing: 0.7, fontWeight: 700, textTransform: 'uppercase',
          }}>
            <span style={{ width: 8, height: 8, borderRadius: 8, background: jp.color }}/>
            {jp.label} · {jp.path.length} steps
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, alignItems: 'center' }}>
            {jp.path.map((id, i) => (
              <React.Fragment key={i}>
                <span style={{
                  padding: '3px 8px', borderRadius: 99,
                  background: `${jp.color}22`, border: `1px solid ${jp.color}44`,
                  fontSize: 11, color: T.text, fontWeight: 600,
                }}>{nodeMap[id]?.l}</span>
                {i < jp.path.length - 1 && (
                  <span style={{ fontSize: 11, color: T.textMute }}>→</span>
                )}
              </React.Fragment>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

window.NavDiagram = NavDiagram;
