// Dashboard — "Today" — the emotional magazine cover

function Dashboard({ onNav }) {
  const wedding = useWedding();
  const { active: activeTasks, toggleTask, addTask, updateTask } = useTasks();
  const g = useGuests();
  const b = useBudget();
  const vendors = useVendors();
  const signals = usePlanningSignals();
  const confidence = usePlanningConfidence();
  const readiness = useReadinessScore();
  const [editingTask, setEditingTask] = React.useState(null);
  const todayLabel = new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' });

  const submitTask = (v) => {
    if (editingTask === 'new') addTask(v);
    else updateTask(editingTask.id, v);
    setEditingTask(null);
  };

  return (
    <div style={{ background: W.bg, paddingBottom: 28, position: 'relative' }}>
      {/* Status bar overlay handled by app shell — leave room */}
      <div style={{ paddingTop: 56 }} />

      {/* Top: brand mark + settings */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '0 22px 14px',
      }}>
        <div style={{
          fontFamily: FONT_DISPLAY, fontStyle: 'italic',
          fontSize: 19, color: W.ink2, letterSpacing: 0.2,
        }}>weddingos</div>
        <button onClick={() => onNav('settings')} style={{
          width: 36, height: 36, borderRadius: 999,
          background: W.card, border: `0.5px solid ${W.line}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer', padding: 0,
        }}>
          <Icon name="sparkle" size={15} color={W.ink2}/>
        </button>
      </div>

      {/* Greeting */}
      <div style={{ padding: '6px 22px 18px' }}>
        <div style={{
          fontFamily: FONT_UI, fontSize: 13, color: W.muted,
          letterSpacing: 0.3, marginBottom: 6,
        }}>{todayLabel}</div>
        <div style={{
          fontFamily: FONT_DISPLAY, fontSize: 32, fontWeight: 500,
          color: W.ink, lineHeight: 1.05, letterSpacing: -0.4,
        }}>
          {wedding.brides
            ? <>Good morning, <span style={{ fontStyle: 'italic' }}>{wedding.brides}.</span></>
            : <>Good morning.</>}
        </div>
        <div style={{
          fontFamily: FONT_UI, fontSize: 14.5, color: W.ink2,
          marginTop: 8, lineHeight: 1.4, maxWidth: 290,
        }}>
          {wedding.isEmpty
            ? <>Welcome. Start by setting up your wedding basics.</>
            : <>You're on track. {confidence}</>}
        </div>
      </div>

      {/* The hero: countdown card — or setup card if empty */}
      {wedding.isEmpty ? (
        <div style={{ padding: '0 16px 18px' }}>
          <Card style={{
            padding: '26px 24px',
            background: W.cardDeep, color: '#f5efe2', border: 'none',
            boxShadow: '0 12px 32px -16px rgba(29,24,18,0.45)',
          }}>
            <div style={{
              fontFamily: FONT_UI, fontSize: 10.5, fontWeight: 600,
              letterSpacing: 1.8, textTransform: 'uppercase',
              color: 'rgba(245,239,226,0.55)',
            }}>Let's begin</div>
            <div style={{
              fontFamily: FONT_DISPLAY, fontSize: 28, fontWeight: 500,
              marginTop: 6, letterSpacing: -0.3, lineHeight: 1.15,
            }}>
              Set your wedding <span style={{ fontStyle: 'italic' }}>basics</span>
            </div>
            <div style={{
              fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 14,
              color: 'rgba(245,239,226,0.75)', marginTop: 12, lineHeight: 1.45,
              maxWidth: 280,
            }}>
              Names, date, city, guest count, budget. Two minutes — then the rest fills in around it.
            </div>
            <button onClick={() => onNav('settings')} style={{
              marginTop: 20, padding: '12px 18px',
              background: '#f5efe2', color: W.ink, border: 'none', borderRadius: 999,
              cursor: 'pointer',
              fontFamily: FONT_UI, fontSize: 13.5, fontWeight: 500,
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              Set it up
              <Icon name="arrow" size={13} color={W.ink}/>
            </button>
          </Card>
        </div>
      ) : (
        <div style={{ padding: '0 16px 18px' }}>
          <Card style={{
            padding: 0, overflow: 'hidden',
            background: W.cardDeep, color: '#f5efe2',
            border: 'none',
            boxShadow: '0 12px 32px -16px rgba(29,24,18,0.45)',
          }}>
            <div onClick={() => onNav('dayof')} style={{ position: 'relative', padding: '26px 24px 24px', cursor: 'pointer' }}>
              <div style={{
                position: 'absolute', inset: 0, pointerEvents: 'none',
                background: 'radial-gradient(120% 80% at 100% 0%, rgba(199,155,145,0.18), transparent 60%), radial-gradient(80% 60% at 0% 100%, rgba(168,122,79,0.18), transparent 60%)',
              }}/>
              <div style={{ position: 'relative' }}>
                <div style={{
                  fontFamily: FONT_UI, fontSize: 10.5, fontWeight: 600,
                  letterSpacing: 1.8, textTransform: 'uppercase',
                  color: 'rgba(245,239,226,0.55)',
                }}>The Wedding of</div>
                <div style={{
                  fontFamily: FONT_DISPLAY, fontSize: 30, fontWeight: 500,
                  marginTop: 4, letterSpacing: -0.2, lineHeight: 1.1,
                }}>
                  {wedding.brides || 'You'} <span style={{ fontStyle: 'italic', opacity: 0.85 }}>&amp;</span> {wedding.groom || 'Yours'}
                </div>

                <div style={{ marginTop: 22 }}>
                  <div style={{
                    fontFamily: FONT_DISPLAY, fontSize: 104, fontWeight: 400,
                    lineHeight: 0.85, letterSpacing: -4,
                  }}>{wedding.daysUntil != null ? wedding.daysUntil : '—'}</div>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 8 }}>
                    <div style={{
                      fontFamily: FONT_UI, fontSize: 11, fontWeight: 600,
                      color: 'rgba(245,239,226,0.65)', textTransform: 'uppercase', letterSpacing: 1.6,
                      whiteSpace: 'nowrap',
                    }}>Days until</div>
                    <div style={{
                      fontFamily: FONT_DISPLAY, fontStyle: 'italic',
                      fontSize: 20, whiteSpace: 'nowrap',
                    }}>{wedding.dateLabel || 'a date to choose'}</div>
                  </div>
                </div>

                <div style={{
                  marginTop: 18, paddingTop: 14,
                  borderTop: '0.5px solid rgba(245,239,226,0.15)',
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
                    <Icon name="leaf" size={14} color="rgba(245,239,226,0.6)" strokeWidth={1.4}/>
                    <span style={{
                      fontFamily: FONT_UI, fontSize: 12,
                      color: 'rgba(245,239,226,0.75)', whiteSpace: 'nowrap',
                    }}>
                      {wedding.cityShort || wedding.city || 'Add a city'}
                      {wedding.timeLabel ? ` · ${wedding.timeLabel}` : ''}
                    </span>
                  </div>
                  <div style={{
                    fontFamily: FONT_UI, fontSize: 12, fontWeight: 500,
                    color: '#f5efe2', display: 'flex', alignItems: 'center', gap: 4,
                    opacity: 0.85,
                  }}>
                    Open day-of <Icon name="chevron" size={12}/>
                  </div>
                </div>
              </div>
            </div>
          </Card>
        </div>
      )}

      {/* Three stat cards */}
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8,
        padding: '0 16px 24px',
      }}>

        <StatCard label="RSVPs"  value={`${g.attending}/${Math.max(g.total, 1)}`} sub={g.pending > 0 ? `${g.pending} pending` : 'All in'} ring={g.total ? g.attending/g.total : 0} color={W.sage}  onClick={() => onNav('guests')}/>
        <StatCard label="Ready"  value={`${readiness.score}%`} sub="Readiness score" ring={readiness.score/100} color={W.rose}/>
      </div>

      {/* Needs attention */}
      <SectionTitle eyebrow="This week" title="Needs attention" action="See all"
        onAction={() => onNav('guests')}/>
      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 26 }}>
        {signals.slice(0, 3).map(s => (
          <SignalCard key={s.id} signal={s} onClick={() => onNav(s.cta)}/>
        ))}
      </div>

      {/* Your to-dos */}
      <SectionTitle eyebrow="Personal" title="Your to-dos"
        action={<><Icon name="plus" size={12} color={W.clay} strokeWidth={1.8}/> Add</>}
        onAction={() => setEditingTask('new')}/>
      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 26 }}>
        {activeTasks.slice(0, 4).map(t => (
          <TaskCard key={t.id} task={t}
            onToggle={() => toggleTask(t.id)}
            onEdit={() => setEditingTask(t)}/>
        ))}
      </div>

      {/* Vendor payments mini-rail */}
      <SectionTitle eyebrow="Vendors" title="Payments"
        action="Manage" onAction={() => onNav('vendors')}/>
      <div style={{
        display: 'flex', gap: 10, padding: '0 16px 26px',
        overflowX: 'auto', scrollSnapType: 'x mandatory',
      }}>
        {(() => {
          // Show most-actionable vendors first: due → partial → booked → paid → researching
          const order = { due: 0, partial: 1, booked: 2, paid: 3, researching: 4 };
          const list = [...vendors.all]
            .sort((a, b) => (order[a.status] ?? 9) - (order[b.status] ?? 9))
            .slice(0, 6);
          if (list.length === 0) {
            return (
              <Card style={{ padding: 16, minWidth: 220 }}>
                <div style={{
                  fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 14, color: W.muted,
                }}>No vendors yet. Add one in the Vendors view.</div>
              </Card>
            );
          }
          return list.map(v => {
            const tone =
              v.status === 'due'     ? 'amber'   :
              v.status === 'paid'    ? 'neutral' :
              v.status === 'partial' ? 'clay'    :
              v.status === 'booked'  ? 'sage'    : 'neutral';
            const label =
              v.status === 'due'         ? (v.next || 'Due')   :
              v.status === 'paid'        ? 'Paid'               :
              v.status === 'partial'     ? 'In progress'        :
              v.status === 'booked'      ? 'Booked'             :
              v.status === 'researching' ? 'Researching'        : v.status;
            return (
              <VendorChip key={v.id} name={v.name} status={label}
                amount={v.total || v.paid || 0} tone={tone}/>
            );
          });
        })()}
      </div>

      {/* Weekly rhythm */}
      <SectionTitle eyebrow="Snapshot" title="This week"/>
      <div style={{ padding: '0 16px 32px' }}>
        <Card style={{ padding: 18 }}>
          <WeekStrip/>
        </Card>
      </div>

      {editingTask && (
        <FormSheet
          title={editingTask === 'new' ? 'Add a task' : 'Edit task'}
          eyebrow={editingTask === 'new' ? 'New' : 'Edit'}
          fields={taskFields(wedding.brides, wedding.groom)}
          initial={editingTask === 'new' ? {} : editingTask}
          submitLabel={editingTask === 'new' ? 'Add' : 'Save'}
          onClose={() => setEditingTask(null)}
          onSubmit={submitTask}
          onDelete={editingTask !== 'new' ? () => {
            updateTask(editingTask.id, { dismissed: true });
            setEditingTask(null);
          } : null}
        />
      )}
    </div>
  );
}

function taskFields(brides, groom) {
  return [
    { name: 'title', label: 'Task', type: 'text',
      placeholder: 'e.g. Confirm florist final payment' },
    { name: 'status', label: 'Status', type: 'choice', default: 'assigned',
      options: [
        { value: 'assigned',   label: 'Assigned' },
        { value: 'inProgress', label: 'In progress', color: '#a87a4f' },
        { value: 'done',       label: 'Done',        color: '#6f8a6a' },
      ] },
    { name: 'assignedTo', label: 'Owner', type: 'choice', default: 'shared',
      options: [
        { value: 'sloane', label: brides || 'Side 1', color: '#a87a4f' },
        { value: 'theo',   label: groom  || 'Side 2', color: '#8a9a85' },
        { value: 'shared', label: 'Shared' },
      ] },
    { name: 'kind',  label: 'Kind', type: 'choice', default: 'todo',
      options: [
        { value: 'todo',    label: 'To-do' },
        { value: 'payment', label: 'Payment', color: '#a87a4f' },
        { value: 'rsvp',    label: 'RSVP',    color: '#8a9a85' },
        { value: 'event',   label: 'Event',   color: '#c79b91' },
      ] },
    { name: 'due',   label: 'Due', type: 'text',
      placeholder: 'e.g. Fri Sep 12, This week, EOD' },
    { name: 'notes', label: 'Notes', type: 'textarea', rows: 3,
      placeholder: 'Anything to remember' },
  ];
}

function StatCard({ label, value, sub, ring, color, onClick }) {
  return (
    <Card onClick={onClick} style={{
      padding: 14, display: 'flex', flexDirection: 'column', gap: 10,
      cursor: onClick ? 'pointer' : 'default',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{
          fontFamily: FONT_UI, fontSize: 10.5, fontWeight: 600,
          letterSpacing: 1.4, textTransform: 'uppercase', color: W.muted,
        }}>{label}</div>
        <ProgressRing value={ring} size={26} stroke={3} color={color}/>
      </div>
      <div>
        <div style={{
          fontFamily: FONT_DISPLAY, fontSize: 26, fontWeight: 500,
          color: W.ink, letterSpacing: -0.4, lineHeight: 1,
        }}>{value}</div>
        <div style={{
          fontFamily: FONT_UI, fontSize: 11.5, color: W.muted,
          marginTop: 4,
        }}>{sub}</div>
      </div>
    </Card>
  );
}

function AssigneeAvatar({ who, size = 18 }) {
  const wedding = useWedding();
  const s = wedding.brides[0] || 'S';
  const t = wedding.groom[0]  || 'T';
  const dotSize = size;
  const dot = (letter, bg) => (
    <div style={{
      width: dotSize, height: dotSize, borderRadius: 999,
      background: bg, color: W.bg,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: FONT_UI, fontSize: dotSize * 0.55, fontWeight: 600,
      letterSpacing: 0,
      flexShrink: 0,
    }}>{letter}</div>
  );
  if (who === 'shared') {
    return (
      <div style={{ display: 'flex' }}>
        {dot(s, W.clay)}
        <div style={{ marginLeft: -dotSize * 0.4 }}>{dot(t, W.sage)}</div>
      </div>
    );
  }
  if (who === 'theo') return dot(t, W.sage);
  return dot(s, W.clay);
}

function TaskCard({ task, onToggle, onEdit }) {
  const kindMeta = {
    payment: { tone: 'amber', icon: 'wallet', label: 'Payment' },
    rsvp:    { tone: 'sage',  icon: 'users',  label: 'RSVP'    },
    event:   { tone: 'rose',  icon: 'calendar', label: 'Event' },
    todo:    { tone: 'neutral', icon: 'check', label: 'To-do' },
  };
  const m = kindMeta[task.kind] || kindMeta.todo;
  const status = task.status || (task.done ? 'done' : 'assigned');
  const done = status === 'done';
  const inProg = status === 'inProgress';
  return (
    <Card onClick={onEdit} style={{
      padding: 14, display: 'flex', alignItems: 'center', gap: 14,
      opacity: done ? 0.55 : 1, transition: 'opacity 200ms ease',
      cursor: onEdit ? 'pointer' : 'default',
    }}>
      <button onClick={(e) => { e.stopPropagation(); onToggle && onToggle(); }} style={{
        width: 40, height: 40, borderRadius: 999,
        background: done ? W.ink : (inProg ? '#fbf6ea' : '#fbf6ea'),
        border: done ? `0.5px solid ${W.ink}`
              : inProg ? `1.5px solid ${W.clay}`
              : `0.5px solid ${W.lineSoft}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0, padding: 0, cursor: onToggle ? 'pointer' : 'default',
        transition: 'all 200ms ease',
        position: 'relative',
      }}>
        <Icon
          name={done ? 'check' : m.icon}
          size={done ? 16 : 18}
          color={done ? W.bg : (inProg ? W.clay : W.clayDeep)}
          strokeWidth={done ? 1.8 : 1.4}/>
        {inProg && (
          <span style={{
            position: 'absolute', top: -3, right: -3,
            width: 12, height: 12, borderRadius: 999, background: W.clay,
            border: `1.5px solid ${W.card}`,
            animation: 'wos-pulse 1.6s ease-in-out infinite',
          }}/>
        )}
      </button>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3 }}>
          <Pill tone={m.tone} style={{ padding: '3px 7px', fontSize: 9.5 }}>{m.label}</Pill>
          <span style={{
            fontFamily: FONT_UI, fontSize: 11.5, color: W.muted,
          }}>{task.due}</span>
          {inProg && (
            <span style={{
              fontFamily: FONT_UI, fontSize: 9.5, fontWeight: 600,
              letterSpacing: 1.2, textTransform: 'uppercase', color: W.clay,
            }}>· In progress</span>
          )}
          {task.assignedTo && (
            <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center' }}>
              <AssigneeAvatar who={task.assignedTo}/>
            </div>
          )}
        </div>
        <div style={{
          fontFamily: FONT_UI, fontSize: 14.5, fontWeight: 500,
          color: W.ink, lineHeight: 1.25,
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          textDecoration: done ? 'line-through' : 'none',
          textDecorationColor: W.muted,
        }}>{task.title}</div>
        {task.notes && !done && (
          <div style={{
            fontFamily: FONT_UI, fontSize: 11.5, color: W.muted, marginTop: 4,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
            fontStyle: 'italic',
          }}>{task.notes}</div>
        )}
      </div>
      {task.amount ? (
        <div style={{
          fontFamily: FONT_DISPLAY, fontSize: 18, color: W.ink, letterSpacing: -0.2,
        }}>{fmt$(task.amount)}</div>
      ) : (
        <Icon name="chevron" size={14} color={W.faint}/>
      )}
    </Card>
  );
}

function VendorChip({ name, status, amount, tone }) {
  return (
    <Card style={{
      padding: 14, minWidth: 168, flexShrink: 0, scrollSnapAlign: 'start',
    }}>
      <Pill tone={tone} style={{ padding: '3px 8px', fontSize: 9.5 }}>{status}</Pill>
      <div style={{
        fontFamily: FONT_UI, fontSize: 13.5, fontWeight: 500,
        color: W.ink, marginTop: 9, lineHeight: 1.2,
      }}>{name}</div>
      <div style={{
        fontFamily: FONT_DISPLAY, fontSize: 22, color: W.ink,
        letterSpacing: -0.3, marginTop: 6,
      }}>{fmt$(amount)}</div>
    </Card>
  );
}

function WeekStrip() {
  const { active: tasks } = useTasks();
  // Build the current Mon-Sun week (today highlighted), with a dot when an
  // active task or payment falls on that day.
  const today = new Date();
  const day = today.getDay(); // 0=Sun..6=Sat
  const mondayOffset = day === 0 ? -6 : 1 - day;
  const monday = new Date(today.getFullYear(), today.getMonth(), today.getDate() + mondayOffset);
  const labels = ['M','T','W','T','F','S','S'];
  // tasks-by-day index for dot rendering and upcoming list
  const taskByDay = {};
  (tasks || []).forEach(t => {
    const dt = t.dueISO ? new Date(t.dueISO) : null;
    if (!dt) return;
    const k = dt.toDateString();
    (taskByDay[k] ||= []).push(t);
  });
  const days = labels.map((d, i) => {
    const dt = new Date(monday.getFullYear(), monday.getMonth(), monday.getDate() + i);
    const isToday = dt.toDateString() === today.toDateString();
    const list = taskByDay[dt.toDateString()] || [];
    const dot = list.some(t => t.kind === 'payment') ? W.clay
              : list.length ? W.rose
              : null;
    return { d, n: dt.getDate(), dot, today: isToday, dt, list };
  });
  // Upcoming list · top 2 active tasks (kept simple; works even without ISO dates).
  // Falls back to task.due text for the day label so we cover both the
  // demo data (string `due` field like "Due Friday") and parsed dates.
  const upcoming = (tasks || [])
    .filter(t => !t.done && t.title)
    .slice(0, 2)
    .map(t => ({
      task: t,
      // Try to derive a short weekday from dueISO; otherwise use `due` directly.
      dayLabel: t.dueISO
        ? ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'][new Date(t.dueISO).getDay()]
        : (t.due || '').replace(/^Due /, '').slice(0, 6),
    }));
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 14 }}>
        {days.map((day, i) => (
          <div key={i} style={{
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7,
            width: 32,
          }}>
            <div style={{
              fontFamily: FONT_UI, fontSize: 10, fontWeight: 600,
              letterSpacing: 1, color: W.muted, textTransform: 'uppercase',
            }}>{day.d}</div>
            <div style={{
              width: 32, height: 32, borderRadius: 999,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: FONT_DISPLAY, fontSize: 16,
              color: day.today ? W.bg : W.ink,
              background: day.today ? W.ink : 'transparent',
              fontWeight: 500,
            }}>{day.n}</div>
            <div style={{
              width: 5, height: 5, borderRadius: 999,
              background: day.dot || 'transparent',
            }}/>
          </div>
        ))}
      </div>
      <div style={{
        paddingTop: 14, borderTop: `0.5px solid ${W.lineSoft}`,
      }}>
        {upcoming.length === 0 ? (
          <div style={{
            fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 13,
            color: W.muted, lineHeight: 1.5,
          }}>
            Nothing scheduled this week.
          </div>
        ) : upcoming.map(({ task, dayLabel }, i) => (
          <div key={task.id || i} style={{
            display: 'flex', gap: 12, alignItems: 'center',
            marginTop: i === 0 ? 0 : 10,
          }}>
            <div style={{
              width: 5, height: 5, borderRadius: 999,
              background: task.kind === 'payment' ? W.clay : W.rose,
            }}/>
            <div style={{
              flex: 1, fontFamily: FONT_UI, fontSize: 13, color: W.ink2,
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
            }}>{task.title}</div>
            <div style={{
              fontFamily: FONT_UI, fontSize: 12, color: W.muted,
            }}>{dayLabel}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard });
