// Nawi mobile UI kit — reusable components
// Mirrors the production widgets/ Flutter files. Visual recreation,
// not real production code.

const { useState, useEffect, useRef } = React;

// ─── Material Symbols glyph ────────────────────────────────────────
function Icon({ name, size = 20, color, rounded = false, fill = false, style = {} }) {
  return (
    <span
      style={{
        fontFamily: rounded ? '"Material Symbols Rounded"' : '"Material Symbols Outlined"',
        fontWeight: 400,
        fontSize: size,
        lineHeight: 1,
        color: color || 'inherit',
        display: 'inline-block',
        fontVariationSettings: fill ? "'FILL' 1" : "'FILL' 0",
        userSelect: 'none',
        ...style,
      }}
    >
      {name}
    </span>
  );
}

// ─── Tap-down scale wrapper (button micro-interaction) ────────────
function Tap({ children, onClick, scale = 0.97, style = {}, className = '' }) {
  const [down, setDown] = useState(false);
  return (
    <div
      className={className}
      onPointerDown={() => setDown(true)}
      onPointerUp={() => setDown(false)}
      onPointerLeave={() => setDown(false)}
      onPointerCancel={() => setDown(false)}
      onClick={onClick}
      style={{
        transform: down ? `scale(${scale})` : 'scale(1)',
        transition: 'transform 150ms cubic-bezier(0.4,0,0.2,1)',
        cursor: 'pointer',
        ...style,
      }}
    >
      {children}
    </div>
  );
}

// ─── Section header (Today / Inbox / Settings) ────────────────────
function SectionHeader({ title, subtitle, trailing, isDark }) {
  return (
    <div style={{ padding: '8px 16px 16px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div>
          <h1 style={{
            margin: 0,
            fontSize: 28, fontWeight: 700,
            letterSpacing: '-0.3px', lineHeight: 1.15,
            color: isDark ? '#EDEDED' : '#121316',
          }}>{title}</h1>
          {subtitle && (
            <div style={{
              marginTop: 6,
              fontSize: 14, fontWeight: 400,
              color: isDark ? '#71747A' : '#8A8D93',
              lineHeight: 1.4,
            }}>{subtitle}</div>
          )}
        </div>
        {trailing}
      </div>
    </div>
  );
}

// ─── Round task checkbox with mint snap on completion ─────────────
function TaskCheckbox({ done, onTap, borderColor }) {
  const [animating, setAnimating] = useState(false);
  const handle = (e) => {
    e.stopPropagation();
    setAnimating(true);
    setTimeout(() => { onTap?.(); setAnimating(false); }, 200);
  };
  return (
    <div
      onClick={handle}
      style={{
        width: 34, height: 34,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        cursor: 'pointer', flexShrink: 0,
      }}
    >
      <div
        style={{
          width: 20, height: 20,
          borderRadius: '50%',
          border: `1.5px solid ${done || animating ? '#00E676' : (borderColor || '#8A8D93')}`,
          background: done || animating ? '#00E676' : 'transparent',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          transform: animating ? 'scale(0.85)' : 'scale(1)',
          transition: 'all 200ms cubic-bezier(0.215,0.610,0.355,1)',
        }}
      >
        {(done || animating) && <Icon name="check" size={12} color="white" rounded />}
      </div>
    </div>
  );
}

// ─── Priority flag — outlined for P3, filled for P1/P2 ────────────
function PriorityFlag({ priority }) {
  if (priority === 'p4') return null;
  const colors = { p1: '#EF4444', p2: '#F59E0B', p3: '#4D21FC' };
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 1, paddingLeft: 10 }}>
      <Icon
        name={priority === 'p3' ? 'flag' : 'flag'}
        size={16}
        color={colors[priority]}
        fill={priority !== 'p3'}
      />
      {priority === 'p1' && (
        <span style={{ fontSize: 11, fontWeight: 700, color: '#EF4444', lineHeight: 1 }}>!</span>
      )}
    </div>
  );
}

// ─── Task tile (mirrors NawiTaskTile) ─────────────────────────────
function TaskTile({ task, isDark, onToggle, onTap }) {
  const fg1 = isDark ? '#EDEDED' : '#121316';
  const fg2 = isDark ? '#71747A' : '#8A8D93';
  const divider = isDark ? '#1F1F22' : '#EBEBEB';
  const showStripe = !!task.quadrantColor;

  const dueColor = task.dueIs === 'overdue' ? '#EF4444'
                : task.dueIs === 'today'   ? '#F59E0B'
                : fg2;

  return (
    <Tap onClick={onTap} scale={1} style={{ background: 'transparent' }}>
      <div style={{ padding: '0 20px' }}>
        <div style={{ display: 'flex', alignItems: 'center', minHeight: 60, padding: '10px 0' }}>
          {showStripe && (
            <div style={{
              width: 3, height: 36, marginRight: 10,
              borderRadius: 2, background: task.quadrantColor,
            }} />
          )}
          <TaskCheckbox done={task.done} onTap={() => onToggle?.(task.id)} borderColor={fg2} />
          <div style={{ marginLeft: 14, flex: 1, minWidth: 0 }}>
            <div style={{
              fontSize: 15, fontWeight: 400, lineHeight: 1.3,
              color: task.done ? fg2 : fg1,
              textDecoration: task.done ? 'line-through' : 'none',
              textDecorationColor: fg2,
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
            }}>{task.title}</div>
            {task.meta?.length > 0 && (
              <div style={{
                marginTop: 4,
                fontSize: 11, fontWeight: 500, color: fg2, lineHeight: 1.2,
                display: 'flex', alignItems: 'center', gap: 0,
                whiteSpace: 'nowrap', overflow: 'hidden',
              }}>
                {task.meta.map((m, i) => (
                  <React.Fragment key={i}>
                    {i > 0 && <span style={{ margin: '0 6px' }}> · </span>}
                    {m.dot && <span style={{
                      width: 6, height: 6, borderRadius: '50%',
                      background: m.dot, marginRight: 4, display: 'inline-block',
                    }} />}
                    {m.icon && <Icon name={m.icon} size={11} color={fg2} style={{ marginRight: 2 }} />}
                    <span style={{ color: m.color || fg2 }}>{m.label}</span>
                  </React.Fragment>
                ))}
              </div>
            )}
          </div>
          <PriorityFlag priority={task.priority} />
        </div>
        <div style={{ height: 1, background: divider, marginLeft: (showStripe ? 13 : 0) + 54 }} />
      </div>
    </Tap>
  );
}

// ─── App bar (solid, 0 elevation, hairline scrolled-under) ────────
function AppBar({ title, leading, actions, isDark }) {
  return (
    <div style={{
      height: 56,
      display: 'flex', alignItems: 'center',
      padding: '0 4px 0 4px',
      background: isDark ? '#050505' : '#FAFAFA',
      borderBottom: `1px solid ${isDark ? '#1F1F22' : '#EBEBEB'}`,
    }}>
      {leading || <div style={{ width: 44 }} />}
      <div style={{
        flex: 1,
        fontSize: 17, fontWeight: 700,
        color: isDark ? '#EDEDED' : '#121316',
        paddingLeft: 4,
      }}>{title}</div>
      <div style={{ display: 'flex', gap: 0, paddingRight: 4 }}>{actions}</div>
    </div>
  );
}

function IconBtn({ name, onClick, color, size = 22 }) {
  return (
    <Tap onClick={onClick} style={{
      width: 44, height: 44,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      borderRadius: '50%',
    }}>
      <Icon name={name} size={size} color={color || '#8A8D93'} />
    </Tap>
  );
}

// ─── Bottom nav (selected item expands into a pill) ───────────────
function BottomNav({ current, onTap, isDark }) {
  const items = [
    { id: 'today',  icon: 'today',            label: 'Today'  },
    { id: 'inbox',  icon: 'inbox',            label: 'Inbox'  },
    { id: 'matrix', icon: 'dashboard',        label: 'Matrix' },
    { id: 'cal',    icon: 'calendar_month',   label: 'Calendar' },
    { id: 'me',     icon: 'person_outline',   label: 'You'    },
  ];
  const primary = isDark ? '#8B6FFF' : '#4D21FC';
  return (
    <div style={{
      background: isDark ? '#111112' : '#FFFFFF',
      borderTop: `1px solid ${isDark ? '#1F1F22' : '#EBEBEB'}`,
      padding: '8px 12px 14px',
      display: 'flex', justifyContent: 'space-around', alignItems: 'center',
    }}>
      {items.map(item => {
        const sel = item.id === current;
        return (
          <Tap key={item.id} onClick={() => onTap(item.id)} scale={0.95} style={{
            display: 'flex', alignItems: 'center', gap: sel ? 10 : 0,
            padding: sel ? '8px 16px' : '8px 12px',
            borderRadius: 16,
            background: sel ? (isDark ? 'rgba(106,66,255,0.15)' : 'rgba(77,33,252,0.10)') : 'transparent',
            transition: 'all 350ms cubic-bezier(0.215,0.610,0.355,1)',
          }}>
            <Icon name={item.icon} size={22} color={sel ? primary : (isDark ? '#71747A' : '#8A8D93')} fill={sel} />
            {sel && (
              <span style={{
                fontSize: 13, fontWeight: 600, letterSpacing: 0.2,
                color: primary,
              }}>{item.label}</span>
            )}
          </Tap>
        );
      })}
    </div>
  );
}

// ─── Floating action button (violet, circular, with halo) ─────────
function FAB({ onClick, isDark }) {
  return (
    <Tap onClick={onClick} scale={0.95} style={{
      position: 'absolute',
      right: 20, bottom: 86,
      width: 56, height: 56,
      borderRadius: 28,
      background: isDark ? '#6A42FF' : '#4D21FC',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      boxShadow: '0 8px 24px rgba(77,33,252,0.32)',
      zIndex: 5,
    }}>
      <Icon name="add" size={28} color="white" rounded />
    </Tap>
  );
}

// ─── Bottom-sheet header (✕ / title / ✓) ──────────────────────────
function SheetHeader({ title, onCancel, onConfirm, isDark, confirmDisabled }) {
  return (
    <>
      <div style={{
        width: 36, height: 4, borderRadius: 2,
        background: isDark ? '#2A2A2E' : '#DDDDDD',
        margin: '12px auto 4px',
      }} />
      <div style={{
        display: 'grid', gridTemplateColumns: '44px 1fr 44px',
        alignItems: 'center', padding: '8px 16px',
      }}>
        <Tap onClick={onCancel} scale={0.92} style={{
          width: 44, height: 44, borderRadius: '50%',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="close" size={22} color={isDark ? '#71747A' : '#8A8D93'} rounded />
        </Tap>
        <div style={{
          textAlign: 'center',
          fontSize: 16, fontWeight: 600,
          color: isDark ? '#EDEDED' : '#121316',
        }}>{title}</div>
        <Tap onClick={confirmDisabled ? null : onConfirm} scale={0.92} style={{
          width: 44, height: 44, borderRadius: '50%',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          opacity: confirmDisabled ? 0.35 : 1,
        }}>
          <Icon name="check" size={22} color={isDark ? '#8B6FFF' : '#4D21FC'} rounded />
        </Tap>
      </div>
    </>
  );
}

// ─── Toast (auto-dismiss success / undo) ──────────────────────────
function Toast({ toast, isDark, onUndo }) {
  if (!toast) return null;
  const iconMap = {
    success: { name: 'check_circle', color: '#00D084' },
    error:   { name: 'error',        color: '#EF4444' },
    info:    { name: 'info',         color: '#0EA5E9' },
    undo:    { name: 'undo',         color: isDark ? '#71747A' : '#8A8D93' },
  };
  const ic = iconMap[toast.type] || iconMap.success;
  return (
    <div style={{
      position: 'absolute', left: 16, right: 16, bottom: 96,
      background: isDark ? '#111112' : '#FFFFFF',
      border: `1px solid ${isDark ? '#1F1F22' : '#EBEBEB'}`,
      borderRadius: 12,
      padding: '12px 12px 12px 16px',
      display: 'flex', alignItems: 'center', gap: 12,
      boxShadow: isDark ? 'none' : '0 4px 6px rgba(0,0,0,0.07), 0 1px 2px rgba(0,0,0,0.03)',
      zIndex: 30,
      animation: 'nawiSlideUp 250ms cubic-bezier(0.215,0.610,0.355,1)',
    }}>
      <Icon name={ic.name} size={20} color={ic.color} rounded />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 14, fontWeight: toast.subtitle ? 600 : 500,
          color: isDark ? '#EDEDED' : '#121316', lineHeight: 1.3,
        }}>{toast.title}</div>
        {toast.subtitle && (
          <div style={{
            fontSize: 12, color: isDark ? '#71747A' : '#8A8D93',
            marginTop: 2, lineHeight: 1.3,
          }}>{toast.subtitle}</div>
        )}
      </div>
      {toast.type === 'undo' && (
        <Tap onClick={onUndo} style={{ padding: '4px 8px' }}>
          <span style={{
            fontSize: 13, fontWeight: 600,
            color: isDark ? '#8B6FFF' : '#4D21FC',
          }}>Undo</span>
        </Tap>
      )}
    </div>
  );
}

// Export to window so other babel scripts can use them
Object.assign(window, {
  Icon, Tap, SectionHeader, TaskCheckbox, PriorityFlag, TaskTile,
  AppBar, IconBtn, BottomNav, FAB, SheetHeader, Toast,
});
