import { useEffect, useMemo, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import Layout from '../components/Layout';
import SortTh from '../components/SortTh';
import { supabase } from '../lib/supabase';
import { useAuth } from '../context/AuthContext';
import { useSortable } from '../hooks/useSortable';

function smoothCurve(pts) {
  if (pts.length < 2) return '';
  let d = `M${pts[0][0].toFixed(1)},${pts[0][1].toFixed(1)}`;
  for (let i = 1; i < pts.length; i++) {
    const [x0, y0] = pts[i - 1]; const [x1, y1] = pts[i];
    const cpX = (x0 + x1) / 2;
    d += ` C${cpX.toFixed(1)},${y0.toFixed(1)} ${cpX.toFixed(1)},${y1.toFixed(1)} ${x1.toFixed(1)},${y1.toFixed(1)}`;
  }
  return d;
}

function MiniAreaChart({ data, color = '#F5A523', gradId = 'ag1' }) {
  const W = 90, H = 42;
  if (!data || data.length < 2) return null;
  const max = Math.max(...data, 1);
  const pts = data.map((v, i) => [(i / (data.length - 1)) * W, 4 + (1 - v / max) * (H - 8)]);
  const line = smoothCurve(pts);
  const area = `${line} L${pts[pts.length-1][0].toFixed(1)},${H} L${pts[0][0].toFixed(1)},${H} Z`;
  return (
    <svg width="100%" height={H} viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ display: 'block', overflow: 'hidden' }}>
      <defs>
        <linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">
          <stop offset="5%" stopColor={color} stopOpacity="0.3" />
          <stop offset="95%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={area} fill={`url(#${gradId})`} />
      <path d={line} fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function formatTaskStatus(status) {
  if (status === 'in_progress') return 'In Progress';
  if (status === 'on_hold') return 'On Hold';
  if (status === 'client_review') return 'In Review';
  return status ? status.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()) : '—';
}

export default function ProfilePage() {
  const { currentUser } = useAuth();
  const navigate = useNavigate();
  const { id: profileId } = useParams();
  const [loadingProfile, setLoadingProfile] = useState(false);
  const [profileError, setProfileError] = useState('');
  const [viewedProfile, setViewedProfile] = useState(null);
  const [viewedCompanies, setViewedCompanies] = useState([]);
  const [primaryCompanyAddress, setPrimaryCompanyAddress] = useState('');
  const [editOpen, setEditOpen] = useState(false);
  const [savingProfile, setSavingProfile] = useState(false);
  const [editError, setEditError] = useState('');
  const [editForm, setEditForm] = useState({
    name: '',

    email: '',
    website: '',
    linkedin: '',
  });
  const [avatarUploading, setAvatarUploading] = useState(false);
  const [activityItems, setActivityItems] = useState([]);
  const [profileStats, setProfileStats] = useState(null);
  const [profileTaskItems, setProfileTaskItems] = useState([]);

  const isSelfView = !profileId || profileId === currentUser?.id;

  useEffect(() => {
    let cancelled = false;
    async function loadViewedProfile() {
      if (!profileId || profileId === currentUser?.id) {
        setViewedProfile(null);
        setViewedCompanies([]);
        setPrimaryCompanyAddress('');
        setProfileError('');
        return;
      }
      setLoadingProfile(true);
      setProfileError('');
      try {
        const [{ data: profile, error }] = await Promise.all([
          supabase.from('profiles').select('*').eq('id', profileId).single(),
        ]);
        if (error || !profile) {
          setProfileError('Unable to load profile.');
          return;
        }

        const [{ data: primaryCompany }, { data: memberships }] = await Promise.all([
          profile.company_id
            ? supabase.from('companies').select('id, name, address').eq('id', profile.company_id).maybeSingle()
            : Promise.resolve({ data: null }),
          supabase
            .from('company_members')
            .select('company_id, company:companies(id, name, address)')
            .eq('profile_id', profileId),
        ]);

        if (cancelled) return;
        const names = new Set();
        if (primaryCompany?.name) names.add(primaryCompany.name);
        const primaryAddress = primaryCompany?.address || '';
        (memberships || []).forEach((row) => {
          const n = row?.company?.name;
          if (n) names.add(n);
        });

        setViewedProfile(profile);
        setViewedCompanies([...names]);
        setPrimaryCompanyAddress(primaryAddress);
      } catch (err) {
        if (!cancelled) setProfileError('Unable to load profile.');
      } finally {
        if (!cancelled) setLoadingProfile(false);
      }
    }

    loadViewedProfile();
    return () => {
      cancelled = true;
    };
  }, [profileId, currentUser?.id]);

  useEffect(() => {
    let cancelled = false;
    const uid = isSelfView ? currentUser?.id : profileId;
    if (!uid) return;
    const doneStatuses = ['client_approved', 'invoiced', 'paid'];
    const now = new Date();
    const weeksBack = 10;
    const monthsBack = 8;
    const weekStart = new Date(now); weekStart.setDate(weekStart.getDate() - weeksBack * 7);
    const monthStart = new Date(now); monthStart.setMonth(monthStart.getMonth() - monthsBack);

    Promise.all([
      supabase.from('tasks').select('id', { count: 'exact', head: true }).eq('assigned_to', uid).in('status', doneStatuses),
      supabase.from('tasks').select('completed_at').eq('assigned_to', uid).in('status', doneStatuses).not('completed_at', 'is', null).gte('completed_at', weekStart.toISOString()),
      supabase.from('project_members').select('project_id').eq('profile_id', uid),
      supabase.from('tasks').select('project_id, submitted_at').eq('assigned_to', uid).not('project_id', 'is', null).gte('submitted_at', monthStart.toISOString()),
    ]).then(([completedTotal, completedRecent, members, tasksByMonth]) => {
      if (cancelled) return;

      // weekly chart: count completed tasks per week (oldest → newest)
      const weekBuckets = Array(weeksBack).fill(0);
      (completedRecent.data || []).forEach(t => {
        const msAgo = now - new Date(t.completed_at);
        const weekIdx = weeksBack - 1 - Math.floor(msAgo / (7 * 86400000));
        if (weekIdx >= 0 && weekIdx < weeksBack) weekBuckets[weekIdx]++;
      });

      // monthly chart: distinct active project_ids per month
      const monthBuckets = Array(monthsBack).fill(0);
      const monthSets = Array.from({ length: monthsBack }, () => new Set());
      (tasksByMonth.data || []).forEach(t => {
        const msAgo = now - new Date(t.submitted_at);
        const mIdx = monthsBack - 1 - Math.floor(msAgo / (30.44 * 86400000));
        if (mIdx >= 0 && mIdx < monthsBack) monthSets[mIdx].add(t.project_id);
      });
      monthSets.forEach((s, i) => { monthBuckets[i] = s.size; });

      const projectIds = (members.data || []).map(m => m.project_id);
      const fetchActive = projectIds.length > 0
        ? supabase.from('projects').select('id', { count: 'exact', head: true }).in('id', projectIds).not('status', 'in', '("completed","cancelled")')
        : Promise.resolve({ count: 0 });
      fetchActive.then(active => {
        if (cancelled) return;
        setProfileStats({
          tasksCompleted: completedTotal.count ?? 0,
          tasksChart: weekBuckets,
          activeProjects: active.count ?? 0,
          projectsChart: monthBuckets,
        });
      });
    });
    return () => { cancelled = true; };
  }, [isSelfView, currentUser?.id, profileId]);

  useEffect(() => {
    let cancelled = false;
    const uid = isSelfView ? currentUser?.id : profileId;
    if (!uid) return;

    async function loadProfileTasks() {
      const { data } = await supabase
        .from('tasks')
        .select('id, title, status, submitted_at')
        .eq('assigned_to', uid)
        .in('status', ['in_progress', 'on_hold', 'client_review'])
        .order('submitted_at', { ascending: false })
        .limit(20);

      if (!cancelled) setProfileTaskItems(data || []);
    }

    loadProfileTasks();
    return () => { cancelled = true; };
  }, [isSelfView, currentUser?.id, profileId]);

  useEffect(() => {
    let cancelled = false;
    const uid = isSelfView ? currentUser?.id : profileId;
    if (!uid) return;
    async function loadActivity() {
      const [{ data: actorLogs }, { data: assignedTasks }] = await Promise.all([
        supabase
          .from('activity_log')
          .select('id, created_at, action, task_id, task_title, project_name, project_id')
          .eq('actor_id', uid)
          .order('created_at', { ascending: false })
          .limit(20),
        supabase
          .from('tasks')
          .select('id')
          .eq('assigned_to', uid),
      ]);

      const assignedTaskIds = (assignedTasks || []).map((t) => t.id).filter(Boolean);
      let outcomeLogs = [];
      if (assignedTaskIds.length > 0) {
        const { data } = await supabase
          .from('activity_log')
          .select('id, created_at, action, task_id, task_title, project_name, project_id')
          .in('action', ['task_approved', 'revision_requested'])
          .in('task_id', assignedTaskIds)
          .order('created_at', { ascending: false })
          .limit(20);
        outcomeLogs = data || [];
      }

      if (cancelled) return;
      const merged = [...(actorLogs || []), ...outcomeLogs];
      const deduped = Array.from(new Map(merged.map((item) => [item.id, item])).values());
      deduped.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
      setActivityItems(deduped.slice(0, 10));
    }

    loadActivity();
    return () => { cancelled = true; };
  }, [isSelfView, currentUser?.id, profileId]);

  const profile = useMemo(
    () => isSelfView ? { ...(currentUser || {}), ...(viewedProfile || {}) } : viewedProfile,
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [isSelfView, currentUser?.id, currentUser?.name, currentUser?.email, currentUser?.role, currentUser?.website, currentUser?.linkedin, currentUser?.avatar_url, viewedProfile]
  );
  const companyNames = useMemo(() => {
    if (isSelfView) {
      const names = new Set((currentUser?.companies || []).map((c) => c?.company?.name).filter(Boolean));
      if (currentUser?.company?.name) names.add(currentUser.company.name);
      return [...names];
    }
    return viewedCompanies;
  }, [isSelfView, currentUser, viewedCompanies]);
  const companyAddress = useMemo(() => {
    if (isSelfView) return currentUser?.company?.address || currentUser?.companies?.[0]?.company?.address || '';
    return primaryCompanyAddress || '';
  }, [isSelfView, currentUser, primaryCompanyAddress]);
  const companyDisplayName = useMemo(() => {
    const role = profile?.role;
    if (role === 'team' || role === 'external') return 'Fourge Branding';
    if (companyNames.length > 0) return companyNames.join(', ');
    return 'No Company';
  }, [companyNames, profile?.role]);

  const memberSince = useMemo(() => {
    const d = profile?.created_at ? new Date(profile.created_at) : null;
    return d && !Number.isNaN(d.getTime())
      ? d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
      : null;
  }, [profile?.created_at]);

  const handleAvatarUpload = async (e) => {
    const file = e.target.files?.[0];
    if (!file || !currentUser?.id) return;
    setAvatarUploading(true);
    try {
      const ext = file.name.split('.').pop();
      const path = `${currentUser.id}/avatar.${ext}`;
      const { error: upErr } = await supabase.storage.from('avatars').upload(path, file, { upsert: true });
      if (upErr) { setEditError(upErr.message); return; }
      const { data: { publicUrl } } = supabase.storage.from('avatars').getPublicUrl(path);
      const { data, error: dbErr } = await supabase.from('profiles').update({ avatar_url: publicUrl }).eq('id', currentUser.id).select('*').single();
      if (dbErr) { setEditError(dbErr.message); return; }
      setViewedProfile(data);
    } finally {
      setAvatarUploading(false);
    }
  };
  const dashCardStyle = {
    background: 'var(--card-bg)',
    border: '1px solid var(--border)',
    borderRadius: 8,
    padding: '18px 21px',
    backdropFilter: 'blur(12px)',
    WebkitBackdropFilter: 'blur(12px)',
  };

  const initials = (profile?.name || '')
    .split(' ')
    .map(n => n[0])
    .join('')
    .toUpperCase()
    .slice(0, 2);

  useEffect(() => {
    if (!profile) return;
    setEditForm({
      name: profile.name || '',

      email: profile.email || '',
      website: profile.website || '',
      linkedin: profile.linkedin || '',
    });
    setEditError('');
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [profile?.name, profile?.email, profile?.website, profile?.linkedin]);

  const setEditField = (field) => (e) => setEditForm((prev) => ({ ...prev, [field]: e.target.value }));

  const handleProfileSave = async (e) => {
    e.preventDefault();
    if (!currentUser?.id) return;
    setSavingProfile(true);
    setEditError('');
    try {
      const payload = {
        name: editForm.name.trim(),

        email: editForm.email.trim(),
        website: editForm.website.trim(),
        linkedin: editForm.linkedin.trim(),
      };
      const { data, error } = await supabase
        .from('profiles')
        .update(payload)
        .eq('id', currentUser.id)
        .select('*')
        .single();
      if (error) {
        setEditError(error.message || 'Unable to update profile.');
        return;
      }
      setViewedProfile(data || null);
      setEditOpen(false);
    } finally {
      setSavingProfile(false);
    }
  };


  const ACTION_ICON = {
    task_started:       { bg: 'rgba(96,165,250,0.15)',  color: '#60a5fa', path: <polygon points="6,4 20,12 6,20" fill="currentColor"/> },
    task_resumed:       { bg: 'rgba(96,165,250,0.15)',  color: '#60a5fa', path: <polygon points="6,4 20,12 6,20" fill="currentColor"/> },
    task_submitted:     { bg: 'rgba(74,222,128,0.15)',  color: '#4ade80', path: <><line x1="12" y1="19" x2="12" y2="5" strokeWidth="2" strokeLinecap="round"/><polyline points="5,12 12,5 19,12" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" fill="none"/></> },
    task_approved:      { bg: 'rgba(74,222,128,0.15)',  color: '#4ade80', path: <polyline points="4,13 9,18 20,7" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" fill="none"/> },
    task_on_hold:       { bg: 'rgba(239,68,68,0.15)',   color: '#ef4444', path: <><rect x="6" y="4" width="4" height="16" rx="1" fill="currentColor"/><rect x="14" y="4" width="4" height="16" rx="1" fill="currentColor"/></> },
    task_created:       { bg: 'rgba(167,139,250,0.15)', color: '#a78bfa', path: <><line x1="12" y1="5" x2="12" y2="19" strokeWidth="2" strokeLinecap="round"/><line x1="5" y1="12" x2="19" y2="12" strokeWidth="2" strokeLinecap="round"/></> },
    project_created:    { bg: 'rgba(245,165,35,0.15)',  color: '#F5A523', path: <><path d="M3 7a2 2 0 012-2h4l2 2h8a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V7z" fill="none" strokeWidth="1.5"/></> },
    request_submitted:  { bg: 'rgba(167,139,250,0.15)', color: '#a78bfa', path: <><rect x="5" y="3" width="14" height="18" rx="2" fill="none" strokeWidth="1.5"/><line x1="9" y1="8" x2="15" y2="8" strokeWidth="1.5" strokeLinecap="round"/><line x1="9" y1="12" x2="15" y2="12" strokeWidth="1.5" strokeLinecap="round"/><line x1="9" y1="16" x2="12" y2="16" strokeWidth="1.5" strokeLinecap="round"/></> },
    revision_requested: { bg: 'rgba(245,158,11,0.15)',  color: '#f59e0b', path: <><path d="M4 12a8 8 0 018-8v0a8 8 0 018 8" fill="none" strokeWidth="1.5" strokeLinecap="round"/><polyline points="18,8 20,12 16,12" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" fill="none"/></> },
  };
  const ActionIcon = ({ actionKey, size = 27 }) => {
    const cfg = ACTION_ICON[actionKey] || { bg: 'rgba(255,255,255,0.08)', color: 'rgba(255,255,255,0.4)', path: <circle cx="12" cy="12" r="3" fill="currentColor"/> };
    return (
      <div style={{ width: size, height: size, borderRadius: '50%', background: cfg.bg, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <svg width="13" height="13" viewBox="0 0 24 24" stroke={cfg.color} fill="none" style={{ color: cfg.color }}>{cfg.path}</svg>
      </div>
    );
  };

  const ACTION_LABEL = {
    task_created: 'Task created', task_started: 'Task started', task_on_hold: 'Task put on hold',
    task_resumed: 'Task resumed', task_submitted: 'Task submitted', task_approved: 'Task approved',
    project_created: 'Project created', request_submitted: 'Request submitted', revision_requested: 'Task rejected',
  };

  const toSentenceTitle = (value = '') => {
    if (!value) return '';
    return value.charAt(0).toUpperCase() + value.slice(1);
  };

  const profileTitleStyle = { fontSize: 18, fontWeight: 500, color: 'var(--text-primary)', lineHeight: 1.2 };
  const profileSubStyle = { fontSize: 13, color: 'var(--text-secondary)', marginTop: 3 };
  const profileBodyStyle = { fontSize: 13, color: 'var(--text-primary)' };
  const metaLabelStyle = { fontSize: 11, fontWeight: 500, color: 'var(--text-secondary)', textTransform: 'uppercase', letterSpacing: 0.8 };
  const metaValueStyle = { fontSize: 13, color: 'var(--text-primary)', marginTop: 2 };
  const modalLabelStyle = { fontSize: 11, fontWeight: 500, color: 'var(--text-secondary)', textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 6 };
  const modalInputStyle = {
    fontSize: 13,
    padding: '0 5px',
    textAlign: 'left',
    lineHeight: 1,
  };
  const modalHelperStyle = { fontSize: 12, color: 'var(--text-muted)', marginTop: 6 };
  const modalButtonStyle = {
    lineHeight: 1,
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
  };

  const ProfileTasksInProgressCard = ({ tasks = [] }) => {
    const { sortKey, sortDir, toggle, sort } = useSortable('task');
    const [showAll, setShowAll] = useState(false);
    const rows = sort(tasks.slice(0, 10), (task, key) => {
      if (key === 'task') return task.title || '';
      if (key === 'status') return formatTaskStatus(task.status);
      return '';
    });
    const visibleRows = showAll ? rows : rows.slice(0, 5);

    return (
      <div style={{ ...dashCardStyle, display: 'flex', flexDirection: 'column' }}>
        <div style={{ marginBottom: rows.length > 0 ? 14 : 0, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
          <span style={{ fontSize: 11, fontWeight: 500, color: 'var(--text-secondary)', letterSpacing: 0.8, textTransform: 'uppercase' }}>Tasks In Progress</span>
          {rows.length > 5 && (
            <button type="button" className="dashboard-inline-link" style={{ fontSize: 11, fontWeight: 500, letterSpacing: 0.4, textTransform: 'uppercase' }} onClick={() => setShowAll((value) => !value)}>
              {showAll ? 'Show less' : 'Show all'}
            </button>
          )}
        </div>
        {rows.length === 0 ? (
          <div style={{ fontSize: 13, color: 'var(--text-muted)' }}>No tasks in progress</div>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse', tableLayout: 'fixed' }}>
            <colgroup>
              <col style={{ width: '65%' }} />
              <col style={{ width: '35%' }} />
            </colgroup>
            <thead style={{ background: 'transparent' }}>
              <tr style={{ background: 'transparent' }}>
                <SortTh col="task" sortKey={sortKey} sortDir={sortDir} onSort={toggle} style={{ fontSize: 10, fontWeight: 500, color: 'var(--text-muted)', textAlign: 'left', letterSpacing: 0.6, textTransform: 'uppercase', padding: '0 0 12px 5px', border: 'none', background: 'transparent', verticalAlign: 'top' }}>
                  Task
                </SortTh>
                <SortTh col="status" sortKey={sortKey} sortDir={sortDir} onSort={toggle} style={{ fontSize: 10, fontWeight: 500, color: 'var(--text-muted)', textAlign: 'right', letterSpacing: 0.6, textTransform: 'uppercase', padding: '0 5px 12px 0', border: 'none', background: 'transparent', verticalAlign: 'top' }}>
                  Status
                </SortTh>
              </tr>
            </thead>
            <tbody>
              {visibleRows.map((task) => (
                <tr key={task.id} style={{ background: 'transparent' }}>
                  <td style={{ fontSize: 13, color: 'var(--text-primary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', padding: '5px', border: 'none', background: 'transparent', textAlign: 'left' }}>
                    <button type="button" className="dashboard-inline-link" onClick={() => navigate(`/requests/${task.id}`)}>{task.title}</button>
                  </td>
                  <td style={{ fontSize: 12, color: 'var(--text-primary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', padding: '5px', border: 'none', background: 'transparent', textAlign: 'right' }}>
                    {formatTaskStatus(task.status)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    );
  };

  const ProfileActivityFeed = ({ items }) => (
    <div style={{ ...dashCardStyle }}>
      <div style={{ marginBottom: items.length > 0 ? 14 : 0 }}>
        <span style={{ fontSize: 11, fontWeight: 500, color: 'var(--text-secondary)', letterSpacing: 0.8, textTransform: 'uppercase' }}>Recent Activity</span>
      </div>
      {items.length === 0 ? (
        <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 14 }}>No recent activity</div>
      ) : items.map((e, i) => (
        <div key={e.id} style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: i > 0 ? 10 : 0 }}>
          <ActionIcon actionKey={e.action} />
          <div style={{ flex: 1, minWidth: 0, fontSize: 13, lineHeight: 1.4 }}>
            <span style={{ color: 'var(--text-muted)' }}>{toSentenceTitle(ACTION_LABEL[e.action] || e.action)}</span>
            {e.task_title && e.task_id && (
              <><span style={{ color: 'var(--text-muted)' }}> </span>
              <button type="button" className="dashboard-inline-link" onClick={() => navigate(`/requests/${e.task_id}`)}>{e.task_title}</button></>
            )}
            {e.task_title && !e.task_id && <span style={{ color: 'var(--text-primary)' }}> {e.task_title}</span>}
          </div>
          <span style={{ fontSize: 11, color: 'var(--text-muted)', whiteSpace: 'nowrap', flexShrink: 0 }}>
            {new Date(e.created_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
          </span>
        </div>
      ))}
    </div>
  );

  return (
    <Layout>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
        {loadingProfile && <div style={dashCardStyle}>Loading profile...</div>}
        {!loadingProfile && profileError && <div style={{ ...dashCardStyle, color: 'var(--danger)' }}>{profileError}</div>}
        {!loadingProfile && !profileError && (
        <div className="profile-top-grid">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
          <div style={{ ...dashCardStyle, display: 'flex', alignItems: 'flex-start', gap: 20, position: 'relative' }}>
            <div style={{ position: 'absolute', top: 18, right: 21, bottom: 18, display: 'flex', flexDirection: 'column', alignItems: 'flex-end', justifyContent: 'space-between' }}>
              {isSelfView && (
                <button
                  type="button"
                  className="btn btn-outline"
                  onClick={() => setEditOpen(true)}
                >
                  Edit Profile
                </button>
              )}
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 10, marginTop: 'auto' }}>
                {memberSince && (
                  <div style={{ textAlign: 'right' }}>
                    <div style={metaLabelStyle}>Member Since</div>
                    <div style={metaValueStyle}>{memberSince}</div>
                  </div>
                )}
                {profile?.role && (
                  <div style={{ textAlign: 'right' }}>
                    <div style={metaLabelStyle}>Role</div>
                    <div style={metaValueStyle}>
                      {profile.role === 'team' ? 'Team' : profile.role === 'external' ? 'Subcontractor' : profile.role === 'client' ? 'Client' : profile.role}
                    </div>
                  </div>
                )}
              </div>
            </div>
            <div style={{ width: 140, height: 140, flexShrink: 0, borderRadius: '50%', background: 'var(--card-bg-2)', border: '2px solid #111', outline: '2px solid var(--accent)', outlineOffset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 36, color: 'var(--text-primary)', fontWeight: 500, lineHeight: 1, overflow: 'hidden' }}>
              {profile?.avatar_url
                ? <img src={profile.avatar_url} alt={profile.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                : (initials || '?')}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={profileTitleStyle}>{profile?.name || '—'}</div>
              <div style={profileSubStyle}>
                {companyDisplayName}
              </div>
              <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
                {companyAddress && (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13 }}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--text-muted)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, position: 'relative', top: -2 }}><path d="M12 22s-8-4.5-8-11.8A8 8 0 0112 2a8 8 0 018 8.2c0 7.3-8 11.8-8 11.8z"/><circle cx="12" cy="10" r="3"/></svg>
                    <span style={profileBodyStyle}>{companyAddress}</span>
                  </div>
                )}
                {profile?.email && (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13 }}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--text-muted)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, position: 'relative', top: -2 }}><rect x="2" y="4" width="20" height="16" rx="2"/><polyline points="2,4 12,13 22,4"/></svg>
                    <span style={profileBodyStyle}>{profile.email}</span>
                  </div>
                )}
                {profile?.website && (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13 }}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--text-muted)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, position: 'relative', top: -2 }}><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2a15.3 15.3 0 010 20M12 2a15.3 15.3 0 000 20"/></svg>
                    <a href={profile.website.startsWith('http') ? profile.website : `https://${profile.website}`} target="_blank" rel="noreferrer" style={{ ...profileBodyStyle, textDecoration: 'none' }}>{profile.website.replace(/^https?:\/\/(www\.)?/, '')}</a>
                  </div>
                )}
                {profile?.linkedin && (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13 }}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="var(--text-muted)" style={{ flexShrink: 0, position: 'relative', top: -2 }}><path d="M16 8a6 6 0 016 6v7h-4v-7a2 2 0 00-2-2 2 2 0 00-2 2v7h-4v-7a6 6 0 016-6z"/><rect x="2" y="9" width="4" height="12"/><circle cx="4" cy="4" r="2"/></svg>
                    <a href={profile.linkedin.startsWith('http') ? profile.linkedin : `https://${profile.linkedin}`} target="_blank" rel="noreferrer" style={{ ...profileBodyStyle, textDecoration: 'none' }}>{profile.linkedin.replace(/^https?:\/\/(www\.)?/, '')}</a>
                  </div>
                )}
              </div>
            </div>
          </div>
          {profileStats && (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
              {/* Tasks Completed — weekly */}
              <div style={{ ...dashCardStyle, display: 'flex', flexDirection: 'column', minHeight: 120 }}>
                <div style={{ display: 'flex', alignItems: 'stretch', gap: 21 }}>
                <div style={{ display: 'flex', flexDirection: 'column', flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--text-secondary)', letterSpacing: 0.8, textTransform: 'uppercase', marginBottom: 5 }}>Tasks Completed</div>
                  <div style={{ flex: 1, display: 'flex', alignItems: 'center' }}>
                    <div style={{ fontSize: 30, fontWeight: 400, color: 'var(--text-primary)', letterSpacing: -0.5, lineHeight: 1.1 }}>{profileStats.tasksCompleted}</div>
                  </div>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', justifyContent: 'space-between', flexShrink: 0 }}>
                  <div style={{ width: 27, height: 27, borderRadius: '50%', background: 'rgba(74,222,128,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#4ade80" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" dangerouslySetInnerHTML={{ __html: '<polyline points="4,13 9,18 20,7"/>' }} />
                  </div>
                </div>
                </div>
                <MiniAreaChart data={profileStats.tasksChart} color="#4ade80" gradId="tcGrad" />
              </div>
              {/* Active Projects — monthly */}
              <div style={{ ...dashCardStyle, display: 'flex', flexDirection: 'column', minHeight: 120 }}>
                <div style={{ display: 'flex', alignItems: 'stretch', gap: 21 }}>
                <div style={{ display: 'flex', flexDirection: 'column', flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--text-secondary)', letterSpacing: 0.8, textTransform: 'uppercase', marginBottom: 5 }}>Active Projects</div>
                  <div style={{ flex: 1, display: 'flex', alignItems: 'center' }}>
                    <div style={{ fontSize: 30, fontWeight: 400, color: 'var(--text-primary)', letterSpacing: -0.5, lineHeight: 1.1 }}>{profileStats.activeProjects}</div>
                  </div>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', justifyContent: 'space-between', flexShrink: 0 }}>
                  <div style={{ width: 27, height: 27, borderRadius: '50%', background: 'rgba(245,165,35,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#F5A523" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" dangerouslySetInnerHTML={{ __html: '<path d="M3 7a2 2 0 012-2h4l2 2h8a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V7z" fill="none"/>' }} />
                  </div>
                </div>
                </div>
                <MiniAreaChart data={profileStats.projectsChart} color="#F5A523" gradId="apGrad" />
              </div>
            </div>
          )}
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
            <ProfileTasksInProgressCard tasks={profileTaskItems} />
            <ProfileActivityFeed items={activityItems} />
          </div>
        </div>
        )}
      </div>
      {isSelfView && editOpen && (
        <div
          style={{
            position: 'fixed',
            inset: 0,
            zIndex: 1200,
            background: 'rgba(0,0,0,0.58)',
            backdropFilter: 'blur(6px)',
            WebkitBackdropFilter: 'blur(6px)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            padding: 24,
          }}
          onClick={() => { if (!savingProfile) setEditOpen(false); }}
        >
          <div
            style={{
              ...dashCardStyle,
              width: 'min(434px, 100%)',
              maxHeight: 'calc(100vh - 48px)',
              overflowY: 'auto',
            }}
            onClick={(e) => e.stopPropagation()}
          >
            <div style={{ ...metaLabelStyle, marginBottom: 14 }}>Edit Profile</div>
            <form onSubmit={handleProfileSave}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 20 }}>
                <div style={{ width: 72, height: 72, borderRadius: '50%', background: 'var(--card-bg-2)', border: '2px solid #111', outline: '2px solid var(--accent)', outlineOffset: 0, flexShrink: 0, overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24, color: 'var(--text-primary)', fontWeight: 500 }}>
                  {profile?.avatar_url
                    ? <img src={profile.avatar_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                    : (initials || '?')}
                </div>
                <div>
                  <label htmlFor="avatar-upload" style={{ cursor: 'pointer', display: 'inline-block' }}>
                    <span className="btn btn-outline" style={{ ...modalButtonStyle, display: 'inline-flex', alignItems: 'center' }}>
                      {avatarUploading ? 'Uploading…' : 'Change Photo'}
                    </span>
                  </label>
                  <input id="avatar-upload" type="file" accept="image/*" style={{ display: 'none' }} onChange={handleAvatarUpload} disabled={avatarUploading} />
                  <div style={modalHelperStyle}>JPG, PNG or WebP</div>
                </div>
              </div>
              <div className="form-group">
                <label style={modalLabelStyle}>Name</label>
                <input type="text" value={editForm.name} onChange={setEditField('name')} style={modalInputStyle} />
              </div>

              <div className="form-group">
                <label style={modalLabelStyle}>Email</label>
                <input type="email" value={editForm.email} onChange={setEditField('email')} style={modalInputStyle} />
              </div>
              <div className="form-group">
                <label style={modalLabelStyle}>Website</label>
                <input type="text" value={editForm.website} onChange={setEditField('website')} placeholder="example.com" style={modalInputStyle} />
              </div>
              <div className="form-group">
                <label style={modalLabelStyle}>LinkedIn</label>
                <input type="text" value={editForm.linkedin} onChange={setEditField('linkedin')} placeholder="linkedin.com/in/username" style={modalInputStyle} />
              </div>
              {editError && <div style={{ fontSize: 13, color: 'var(--danger)', marginBottom: 12 }}>{editError}</div>}
              <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 6 }}>
                <button type="button" className="btn btn-outline" onClick={() => setEditOpen(false)} disabled={savingProfile} style={modalButtonStyle}>
                  Cancel
                </button>
                <button type="submit" className="btn btn-outline" disabled={savingProfile} style={modalButtonStyle}>
                  {savingProfile ? 'Saving...' : 'Save Changes'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </Layout>
  );
}
