﻿/* Priority workspace */

function PriorityPage({ tweaks, onBackHome }) {
  const primary = tweaks.primaryColor;
  const [now, setNow] = React.useState(() => new Date());
  const [selectedDate, setSelectedDate] = React.useState(getTodayInputValue);
  const [tasksByDate, setTasksByDate] = React.useState(() => {
    try {
      return JSON.parse(localStorage.getItem(PRIORITY_TASK_STORAGE_KEY) || '{}');
    } catch (err) {
      return {};
    }
  });
  const [draftTask, setDraftTask] = React.useState('');

  React.useEffect(() => {
    const timer = window.setInterval(() => setNow(new Date()), 1000);
    return () => window.clearInterval(timer);
  }, []);

  React.useEffect(() => {
    try {
      localStorage.setItem(PRIORITY_TASK_STORAGE_KEY, JSON.stringify(tasksByDate));
    } catch (err) {}
  }, [tasksByDate]);

  const tasks = tasksByDate[selectedDate] || [];
  const completedTasks = tasks.filter(task => task.done);

  const addTask = (event) => {
    event.preventDefault();
    const text = draftTask.trim();
    if (!text) return;
    const task = {
      id: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
      text,
      done: false,
      createdAt: new Date().toISOString(),
    };
    setTasksByDate(current => ({
      ...current,
      [selectedDate]: [...(current[selectedDate] || []), task],
    }));
    setDraftTask('');
  };

  const updateTask = (taskId, patch) => {
    setTasksByDate(current => ({
      ...current,
      [selectedDate]: (current[selectedDate] || []).map(task =>
        task.id === taskId ? { ...task, ...patch } : task
      ),
    }));
  };

  const removeTask = (taskId) => {
    setTasksByDate(current => ({
      ...current,
      [selectedDate]: (current[selectedDate] || []).filter(task => task.id !== taskId),
    }));
  };

  return (
    <main className="priority-page" style={{
      minHeight: '100vh',
      padding: '118px clamp(20px, 4vw, 64px) 80px',
      background: 'var(--theme-bg)',
      color: 'var(--theme-text)',
      animation: 'fadeIn 0.3s ease',
    }}>
      <div style={{ width: '100%', maxWidth: 1180, margin: '0 auto' }}>
        <div className="priority-header" style={{
          display: 'flex',
          alignItems: 'flex-start',
          justifyContent: 'space-between',
          gap: 20,
          marginBottom: 28,
        }}>
          <div>
            <div style={{
              fontSize: 12,
              fontWeight: 800,
              letterSpacing: '3px',
              textTransform: 'uppercase',
              color: primary,
              marginBottom: 10,
            }}>Admin workspace</div>
            <h1 style={{
              margin: 0,
              color: 'var(--theme-strong)',
              fontSize: 'clamp(38px, 5vw, 62px)',
              lineHeight: 1.05,
            }}>Priority</h1>
          </div>
          <button type="button" onClick={onBackHome} style={deButtonStyle(primary, false)}>Back home</button>
        </div>

        <PriorityClock now={now}/>
        <FocusGarden tasks={completedTasks} color={primary} date={selectedDate}/>

        <div className="priority-layout" style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
          gap: 18,
          marginTop: 28,
        }}>
          <PriorityPanel title="20-20-20 principle">
            <PriorityLine>20: W</PriorityLine>
            <PriorityLine>20: F</PriorityLine>
            <PriorityLine>20: W</PriorityLine>
          </PriorityPanel>

          <PriorityPanel title="Priority principle">
            <PriorityLine color="#EF4444">BOD Request</PriorityLine>
            <PriorityLine color="#F97316">MTC Project</PriorityLine>
            <PriorityLine color="#3B82F6">Group Request</PriorityLine>
            <PriorityLine color="#22C55E">Personal Project</PriorityLine>
          </PriorityPanel>

          <section className="priority-card priority-task-card" style={{
            gridColumn: '1 / -1',
            padding: 22,
            borderRadius: 20,
            background: 'rgba(var(--theme-surface-rgb),0.22)',
            border: '1px solid rgba(var(--theme-text-rgb),0.08)',
            boxShadow: '0 18px 50px rgba(0,0,0,0.14)',
          }}>
            <div className="priority-task-head" style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              gap: 14,
              marginBottom: 16,
            }}>
              <h2 style={{ margin: 0, color: 'var(--theme-strong)', fontSize: 22 }}>Priority task</h2>
              <PriorityDatePicker
                value={selectedDate}
                onChange={setSelectedDate}
                color={primary}
              />
            </div>

            <form onSubmit={addTask} className="priority-add-row" style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 104px', gap: 10, marginBottom: 16 }}>
              <input
                value={draftTask}
                onChange={event => setDraftTask(event.target.value)}
                placeholder="Add task"
                style={priorityFieldStyle()}
              />
              <button type="submit" style={deButtonStyle(primary, true)}>Add</button>
            </form>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {tasks.length === 0 ? (
                <div style={{
                  padding: '18px 16px',
                  borderRadius: 14,
                  background: 'rgba(var(--theme-bg-rgb),0.3)',
                  border: '1px dashed rgba(var(--theme-text-rgb),0.14)',
                  color: 'rgba(var(--theme-text-rgb),0.52)',
                  fontSize: 14,
                }}>No priority task for this day.</div>
              ) : tasks.map(task => (
                <div key={task.id} className="priority-task-row" style={{
                  display: 'grid',
                  gridTemplateColumns: '32px minmax(0, 1fr) 40px',
                  gap: 10,
                  alignItems: 'center',
                  padding: 10,
                  borderRadius: 14,
                  background: 'rgba(var(--theme-bg-rgb),0.32)',
                  border: '1px solid rgba(var(--theme-text-rgb),0.07)',
                }}>
                  <input
                    type="checkbox"
                    checked={task.done}
                    onChange={event => updateTask(task.id, { done: event.target.checked })}
                    style={{ width: 18, height: 18, accentColor: primary }}
                  />
                  <input
                    value={task.text}
                    onChange={event => updateTask(task.id, { text: event.target.value })}
                    style={{
                      ...priorityFieldStyle(),
                      textDecoration: task.done ? 'line-through' : 'none',
                      color: task.done ? 'rgba(var(--theme-text-rgb),0.46)' : 'var(--theme-text)',
                    }}
                  />
                  <button type="button" onClick={() => removeTask(task.id)} aria-label="Delete task" style={{
                    width: 38,
                    height: 38,
                    borderRadius: 12,
                    border: '1px solid rgba(239,68,68,0.25)',
                    background: 'rgba(239,68,68,0.1)',
                    color: '#EF4444',
                    cursor: 'pointer',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}>
                    <TrashIcon/>
                  </button>
                </div>
              ))}
            </div>
          </section>
        </div>
      </div>
    </main>
  );
}

function PriorityClock({ now }) {
  const blue = '#38BDF8';
  const yellow = '#F5B96B';
  const totalMinutes = now.getMinutes() + now.getSeconds() / 60 + now.getMilliseconds() / 60000;
  const angle = totalMinutes * 6;
  const pointer = priorityPolar(120, 120, 82, angle);
  const pointerOuter = priorityPolar(120, 120, 96, angle);

  return (
    <section style={{
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      minHeight: 270,
      borderRadius: 24,
      background: 'rgba(var(--theme-surface-rgb),0.18)',
      border: '1px solid rgba(var(--theme-text-rgb),0.08)',
      boxShadow: '0 18px 50px rgba(0,0,0,0.14)',
    }}>
      <svg width="260" height="260" viewBox="0 0 240 240" aria-label="20-20-20 clock">
        <circle cx="120" cy="120" r="78" fill="rgba(var(--theme-bg-rgb),0.38)" stroke="rgba(var(--theme-text-rgb),0.08)" strokeWidth="1"/>
        <path d={priorityArcPath(120, 120, 86, 0, 118)} stroke={blue} strokeWidth="20" fill="none" strokeLinecap="round"/>
        <path d={priorityArcPath(120, 120, 86, 122, 238)} stroke={yellow} strokeWidth="20" fill="none" strokeLinecap="round"/>
        <path d={priorityArcPath(120, 120, 86, 242, 360)} stroke={blue} strokeWidth="20" fill="none" strokeLinecap="round"/>
        {Array.from({ length: 12 }).map((_, index) => {
          const tickAngle = index * 30;
          const p1 = priorityPolar(120, 120, 103, tickAngle);
          const p2 = priorityPolar(120, 120, 108, tickAngle);
          return <line key={index} x1={p1.x} y1={p1.y} x2={p2.x} y2={p2.y} stroke="rgba(var(--theme-text-rgb),0.22)" strokeWidth="2" strokeLinecap="round"/>;
        })}
        <line x1={pointer.x} y1={pointer.y} x2={pointerOuter.x} y2={pointerOuter.y} stroke="var(--theme-strong)" strokeWidth="3" strokeLinecap="round"/>
        <circle cx={pointerOuter.x} cy={pointerOuter.y} r="4" fill="var(--theme-strong)"/>
      </svg>
    </section>
  );
}

function FocusGarden({ tasks, color, date }) {
  const plantCount = tasks.length;
  const beds = plantCount > 0 ? tasks : Array.from({ length: 6 }).map((_, index) => ({
    id: `seed-${index}`,
    text: 'Waiting',
    done: false,
    seed: true,
  }));
  const selectedDate = priorityParseDate(date);
  const dayLabel = selectedDate.toLocaleDateString('en-US', {
    weekday: 'short',
    month: 'short',
    day: '2-digit',
  });

  return (
    <section className="priority-card focus-garden" style={{
      marginTop: 18,
      padding: 22,
      borderRadius: 24,
      background: 'linear-gradient(180deg, rgba(var(--theme-surface-rgb),0.24), rgba(var(--theme-bg-rgb),0.26))',
      border: '1px solid rgba(var(--theme-text-rgb),0.08)',
      boxShadow: '0 18px 50px rgba(0,0,0,0.14)',
      overflow: 'hidden',
      position: 'relative',
    }}>
      <svg aria-hidden="true" viewBox="0 0 900 180" preserveAspectRatio="none" style={{
        position: 'absolute',
        left: 0,
        right: 0,
        bottom: 0,
        width: '100%',
        height: '50%',
        opacity: 0.34,
        pointerEvents: 'none',
      }}>
        <path d="M0 128c110-30 191 22 302-4 126-29 206-48 335-11 106 30 170 10 263-15v82H0z" fill="#22C55E"/>
        <path d="M0 148c142-20 246 25 398-2 144-26 256-7 502 7v27H0z" fill="#15803D" opacity="0.55"/>
      </svg>

      <div className="focus-garden-header" style={{
        position: 'relative',
        zIndex: 1,
        display: 'flex',
        alignItems: 'flex-start',
        justifyContent: 'space-between',
        gap: 16,
        marginBottom: 16,
      }}>
        <div>
          <div style={{
            color,
            fontSize: 11,
            fontWeight: 900,
            letterSpacing: '2px',
            textTransform: 'uppercase',
            marginBottom: 6,
          }}>Focus Garden</div>
          <h2 style={{ margin: 0, color: 'var(--theme-strong)', fontSize: 24, lineHeight: 1.15 }}>
            {plantCount} plant{plantCount === 1 ? '' : 's'} grown
          </h2>
        </div>
        <div style={{
          display: 'inline-flex',
          alignItems: 'center',
          gap: 8,
          padding: '9px 12px',
          borderRadius: 999,
          background: `${color}14`,
          border: `1px solid ${color}30`,
          color,
          fontWeight: 900,
          fontSize: 12,
          whiteSpace: 'nowrap',
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M8 3v4M16 3v4M4 9h16M5 5h14a1 1 0 011 1v14a1 1 0 01-1 1H5a1 1 0 01-1-1V6a1 1 0 011-1z"/>
          </svg>
          {dayLabel}
        </div>
      </div>

      <div className="focus-garden-grid" style={{
        position: 'relative',
        zIndex: 1,
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fit, minmax(118px, 1fr))',
        gap: 12,
      }}>
        {beds.map((task, index) => (
          <FocusPlant key={task.id} task={task} index={index} color={color}/>
        ))}
      </div>
    </section>
  );
}

function FocusPlant({ task, index, color }) {
  const tones = ['#22C55E', '#38BDF8', '#F5B96B', '#A855F7', '#F97316', '#10B981'];
  const tone = task.seed ? 'rgba(var(--theme-text-rgb),0.28)' : tones[index % tones.length];
  const height = task.seed ? 22 : 38 + (index % 4) * 8;

  return (
    <div style={{
      minHeight: 132,
      padding: '12px 10px 10px',
      borderRadius: 18,
      background: task.seed ? 'rgba(var(--theme-bg-rgb),0.24)' : 'rgba(var(--theme-bg-rgb),0.34)',
      border: `1px solid ${task.seed ? 'rgba(var(--theme-text-rgb),0.08)' : `${tone}30`}`,
      display: 'grid',
      gridTemplateRows: '1fr auto',
      justifyItems: 'center',
      gap: 8,
    }}>
      <svg width="84" height="78" viewBox="0 0 84 78" fill="none" aria-hidden="true">
        <ellipse cx="42" cy="70" rx="27" ry="5" fill="rgba(var(--theme-text-rgb),0.1)"/>
        <path d={`M42 ${68} C42 ${52} 42 ${44} 42 ${68 - height}`} stroke={task.seed ? 'rgba(var(--theme-text-rgb),0.32)' : '#16A34A'} strokeWidth="4" strokeLinecap="round"/>
        {task.seed ? (
          <>
            <path d="M32 59c7-7 13-7 20 0" stroke="rgba(var(--theme-text-rgb),0.28)" strokeWidth="3" strokeLinecap="round"/>
            <circle cx="42" cy="55" r="4" fill="rgba(var(--theme-text-rgb),0.24)"/>
          </>
        ) : (
          <>
            <path d={`M42 ${58 - index % 3 * 4}c-14-14-28-9-29 7 14 3 24-1 29-7z`} fill={`${tone}cc`}/>
            <path d={`M42 ${52 - index % 2 * 4}c15-16 30-10 31 7-15 4-25-1-31-7z`} fill={tone}/>
            <path d={`M42 ${42 - index % 3 * 3}c-10-18 0-29 12-28 2 13-2 24-12 28z`} fill={`${color}cc`}/>
            <circle cx="42" cy={68 - height} r="4" fill="#FDE68A"/>
          </>
        )}
        <rect x="22" y="60" width="40" height="12" rx="5" fill={task.seed ? 'rgba(var(--theme-text-rgb),0.16)' : 'rgba(120,53,15,0.72)'}/>
      </svg>
      <div style={{
        width: '100%',
        color: task.seed ? 'rgba(var(--theme-text-rgb),0.42)' : 'rgba(var(--theme-text-rgb),0.78)',
        fontSize: 12,
        fontWeight: 800,
        lineHeight: 1.25,
        textAlign: 'center',
        minHeight: 30,
        display: '-webkit-box',
        WebkitLineClamp: 2,
        WebkitBoxOrient: 'vertical',
        overflow: 'hidden',
      }}>{task.seed ? 'Complete a task' : task.text}</div>
    </div>
  );
}

function PriorityPanel({ title, children }) {
  return (
    <section className="priority-card" style={{
      minHeight: 190,
      padding: 22,
      borderRadius: 20,
      background: 'rgba(var(--theme-surface-rgb),0.22)',
      border: '1px solid rgba(var(--theme-text-rgb),0.08)',
      boxShadow: '0 18px 50px rgba(0,0,0,0.14)',
    }}>
      <h2 style={{ margin: '0 0 16px', color: 'var(--theme-strong)', fontSize: 22 }}>{title}</h2>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>{children}</div>
    </section>
  );
}

function PriorityDatePicker({ value, onChange, color }) {
  const today = getTodayInputValue();
  const date = priorityParseDate(value);
  const month = date.toLocaleDateString('en-US', { month: 'short' });
  const weekday = date.toLocaleDateString('en-US', { weekday: 'short' });
  const day = String(date.getDate()).padStart(2, '0');
  const year = date.getFullYear();
  const isToday = value === today;

  const shiftDate = (offset) => {
    const next = priorityParseDate(value);
    next.setDate(next.getDate() + offset);
    onChange(priorityFormatDate(next));
  };

  return (
    <div className="priority-date-picker" style={{
      display: 'grid',
      gridTemplateColumns: '38px minmax(190px, 1fr) 38px auto',
      gap: 8,
      alignItems: 'stretch',
      minWidth: 0,
    }}>
      <button type="button" onClick={() => shiftDate(-1)} aria-label="Previous day" style={priorityDateButtonStyle(color)}>
        <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
          <path d="M15 18l-6-6 6-6"/>
        </svg>
      </button>

      <label style={{
        position: 'relative',
        display: 'grid',
        gridTemplateColumns: '44px minmax(0, 1fr)',
        gap: 10,
        alignItems: 'center',
        minWidth: 0,
        padding: '9px 12px',
        borderRadius: 16,
        border: `1px solid ${isToday ? color : 'rgba(var(--theme-text-rgb),0.1)'}`,
        background: isToday
          ? `linear-gradient(135deg, ${color}22, rgba(var(--theme-bg-rgb),0.42))`
          : 'rgba(var(--theme-bg-rgb),0.42)',
        boxShadow: isToday ? `0 12px 28px ${color}18` : 'none',
        cursor: 'pointer',
      }}>
        <span style={{
          width: 44,
          height: 44,
          borderRadius: 14,
          background: `${color}18`,
          color,
          border: `1px solid ${color}30`,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.1" strokeLinecap="round" strokeLinejoin="round">
            <path d="M8 3v4M16 3v4M4 9h16M5 5h14a1 1 0 011 1v14a1 1 0 01-1 1H5a1 1 0 01-1-1V6a1 1 0 011-1z"/>
          </svg>
        </span>
        <span style={{ minWidth: 0, textAlign: 'left' }}>
          <span style={{
            display: 'block',
            color: 'var(--theme-strong)',
            fontWeight: 900,
            fontSize: 16,
            lineHeight: 1.1,
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
          }}>{weekday}, {month} {day}</span>
          <span style={{
            display: 'block',
            color: isToday ? color : 'rgba(var(--theme-text-rgb),0.55)',
            fontSize: 12,
            fontWeight: 800,
            marginTop: 4,
          }}>{isToday ? 'Today' : year}</span>
        </span>
        <input
          type="date"
          value={value}
          onChange={event => onChange(event.target.value)}
          aria-label="Choose priority date"
          style={{
            position: 'absolute',
            inset: 0,
            opacity: 0,
            cursor: 'pointer',
          }}
        />
      </label>

      <button type="button" onClick={() => shiftDate(1)} aria-label="Next day" style={priorityDateButtonStyle(color)}>
        <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
          <path d="M9 18l6-6-6-6"/>
        </svg>
      </button>

      <button type="button" onClick={() => onChange(today)} style={{
        ...deButtonStyle(color, isToday),
        minHeight: 44,
        padding: '10px 13px',
      }}>Today</button>
    </div>
  );
}

function priorityDateButtonStyle(color) {
  return {
    width: 38,
    minWidth: 38,
    minHeight: 44,
    borderRadius: 14,
    border: `1px solid ${color}35`,
    background: `${color}12`,
    color,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    cursor: 'pointer',
  };
}

function priorityParseDate(value) {
  const [year, month, day] = String(value || getTodayInputValue()).split('-').map(Number);
  return new Date(year || 1970, (month || 1) - 1, day || 1);
}

function priorityFormatDate(date) {
  const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
  return local.toISOString().slice(0, 10);
}

function PriorityLine({ children, color = 'var(--theme-text)' }) {
  return (
    <div style={{
      color,
      fontWeight: 800,
      fontSize: 18,
      lineHeight: 1.35,
    }}>{children}</div>
  );
}

function priorityFieldStyle() {
  return {
    width: '100%',
    minWidth: 0,
    padding: '11px 12px',
    borderRadius: 12,
    border: '1px solid rgba(var(--theme-text-rgb),0.1)',
    background: 'rgba(var(--theme-bg-rgb),0.42)',
    color: 'var(--theme-text)',
    fontFamily: 'Poppins, sans-serif',
    fontSize: 14,
    outline: 'none',
  };
}

function priorityPolar(cx, cy, radius, angle) {
  const radians = (angle - 90) * Math.PI / 180;
  return {
    x: cx + radius * Math.cos(radians),
    y: cy + radius * Math.sin(radians),
  };
}

function priorityArcPath(cx, cy, radius, startAngle, endAngle) {
  const start = priorityPolar(cx, cy, radius, endAngle);
  const end = priorityPolar(cx, cy, radius, startAngle);
  const largeArcFlag = endAngle - startAngle <= 180 ? 0 : 1;
  return `M ${start.x} ${start.y} A ${radius} ${radius} 0 ${largeArcFlag} 0 ${end.x} ${end.y}`;
}
