frappe.ui.form.on("Tax Year Closing Wizard", {
	onload(frm) {
		// Full width
		$(`<style>
			[data-doctype="Tax Year Closing Wizard"] .form-section .section-body,
			[data-doctype="Tax Year Closing Wizard"] .form-column,
			[data-doctype="Tax Year Closing Wizard"] .form-layout,
			[data-doctype="Tax Year Closing Wizard"] .layout-main .layout-main-section,
			[data-doctype="Tax Year Closing Wizard"] .form-page {
				max-width: 100% !important;
			}
		</style>`).appendTo("head");
	},

	refresh(frm) {
		frm.trigger("setup_buttons");
		frm.trigger("render_timeline");
		frm.trigger("render_current_step");
		frm.trigger("render_benefits");
		frm.trigger("render_summary");
		if (frm.doc.company && frm.doc.docstatus === 0) {
			frm.trigger("check_accounts");
		}
	},

	check_accounts(frm) {
		frappe.call({
			method: "taxes_az.setup_accounts.check_required_accounts",
			args: { company: frm.doc.company },
			callback(r) {
				if (!r || !r.message) return;
				const data = r.message;
				if (!data.needs_kassa_accounts || data.missing.length === 0) return;

				let msg = `<p><strong>${__("Required accounts for cash method not found:")}</strong></p><ul>`;
				for (const m of data.missing) {
					msg += `<li><strong>${m.number}</strong> — ${m.name}<br><span style="font-size:11px;color:#666;">${m.description}</span></li>`;
				}
				msg += `</ul>`;

				frappe.msgprint({
					title: __("Accounts not found"),
					message: msg,
					indicator: "orange",
					primary_action: {
						label: __("Create accounts"),
						action() {
							frappe.call({
								method: "taxes_az.setup_accounts.create_missing_accounts",
								args: { company: frm.doc.company },
								freeze: true,
								callback(r2) {
									if (r2 && r2.message && r2.message.created.length > 0) {
										frappe.show_alert({
											message: __("{0} accounts created", [r2.message.created.length]),
											indicator: "green"
										});
									}
									frappe.hide_msgprint();
								}
							});
						}
					}
				});
			}
		});
	},

	setup_buttons(frm) {
		if (frm.doc.docstatus >= 1) return;

		if (!frm.doc.steps || frm.doc.steps.length === 0) {
			frm.add_custom_button(__("Generate Timeline"), () => {
				frm.save().then(() => {
					frappe.call({
						method: "taxes_az.taxes_az.doctype.tax_year_closing_wizard.tax_year_closing_wizard.initialize_wizard",
						args: { name: frm.doc.name },
						freeze: true,
						freeze_message: __("Generating timeline..."),
						callback() { window.location.reload(); }
					});
				});
			}).addClass("btn-primary");
		}

		if ((frm.doc.steps || []).length > 0 && frm.doc.overall_status !== "Completed") {
			frm.add_custom_button(__("Close all periods"), () => {
				// First check SI accounts
				check_and_fix_before_closing(frm, () => {
					run_all_steps_sequentially(frm);
				});
			}).addClass("btn-primary").css({"font-weight": "bold"});
		}

		if ((frm.doc.steps || []).length > 0) {
			frm.add_custom_button(__("FIFO Allocate All"), () => {
				frappe.confirm(
					__("Run FIFO allocation for ALL months? This will recognize revenue and VAT for all received payments."),
					() => {
						frappe.call({
							method: "taxes_az.taxes_az.doctype.tax_year_closing_wizard.tax_year_closing_wizard.allocate_all",
							args: { name: frm.doc.name },
							freeze: true,
							freeze_message: __("Running FIFO allocation for all periods..."),
							callback(r) {
								if (r && r.message) {
									const res = r.message;
									if (res.total_jes === 0) {
										frappe.msgprint({
											title: __("FIFO Allocation"),
											message: __("FIFO allocation already done for all periods. No new allocations."),
											indicator: "orange",
										});
									} else {
										frappe.msgprint({
											title: __("FIFO Allocation — All periods"),
											message: `<div style="font-size:14px;">
												<p>✓ <strong>${res.total_jes}</strong> ${__("Journal Entries created")}</p>
												<p>${__("VAT recognition:")} <strong>${format_azn(res.total_vat)}</strong> (245.1 → 521.3)</p>
												<p>${__("Revenue recognition:")} <strong>${format_azn(res.total_revenue)}</strong> (542 → 601)</p>
												<p>${__("Periods:")} ${res.periods_processed}</p>
											</div>`,
											indicator: "green",
											wide: true,
										});
									}
								}
								window.location.reload();
							}
						});
					}
				);
			}).addClass("btn-primary");
		}
	},

	// ── Timeline Stepper ─────────────────────────────────

	render_timeline(frm) {
		const steps = frm.doc.steps || [];
		if (!steps.length) {
			frm.fields_dict.timeline_html && frm.fields_dict.timeline_html.$wrapper.html(
				`<div style="padding:30px;text-align:center;color:#999;">${__('Click "Generate Timeline" to create the year plan.')}</div>`
			);
			return;
		}

		const cfg = {
			"Completed": { bg: "#d4edda", border: "#28a745", icon: "✓", color: "#155724" },
			"Skipped":   { bg: "#e2e3e5", border: "#6c757d", icon: "—", color: "#383d41" },
			"Active":    { bg: "#fff3cd", border: "#ffc107", icon: "◉", color: "#856404" },
			"Calculated":{ bg: "#cce5ff", border: "#007bff", icon: "◉", color: "#004085" },
			"Pending":   { bg: "#f8f9fa", border: "#dee2e6", icon: "○", color: "#6c757d" },
		};

		let html = '<div style="display:flex;flex-direction:column;gap:2px;">';

		for (const step of steps) {
			const c = cfg[step.status] || cfg["Pending"];
			const is_active = step.status === "Active" || step.status === "Calculated";
			const is_quarterly = step.step_type === "Quarterly";
			const is_annual = step.step_type === "Annual";
			const indent = is_quarterly ? "margin-left:20px;" : (is_annual ? "margin-left:0;border-width:2px;" : "");
			const font_weight = (is_quarterly || is_annual) ? "font-weight:bold;" : "";

			const amount_html = flt(step.tax_amount) > 0
				? `<span style="font-weight:bold;color:#28a745;">${format_azn(step.tax_amount)}</span>`
				: (step.status === "Completed" ? '<span style="color:#28a745;">0.00 AZN</span>' : "");

			const je_list = (step.journal_entries || "").split(",").map(j => j.trim()).filter(Boolean);
			const je_html = je_list.length > 0
				? je_list.map(j => `<a href="/app/journal-entry/${j}" style="font-size:11px;">${j}</a>`).join(", ")
				: "";

			const deadline_html = step.deadline_payment
				? (() => {
					const d = new Date(step.deadline_payment);
					const today = new Date();
					const days = Math.ceil((d - today) / 864e5);
					const urg = days <= 0 ? "color:#dc3545;font-weight:bold;" :
						days <= 14 ? "color:#e67e22;" : "color:#999;";
					return `<span style="font-size:11px;${urg}">⏰ ${step.deadline_payment}</span>`;
				})()
				: "";

			// Completed summary mini-card
			const is_completed = step.status === "Completed";
			let completed_summary = "";
			if (is_completed) {
				const details_lines = (step.details || "").split("\n").filter(l => l.trim());
				const details_short = details_lines.map(l =>
					`<div style="font-size:11px;color:#155724;">${frappe.utils.escape_html(l)}</div>`
				).join("");

				completed_summary = `
					<div style="margin-top:6px;display:flex;gap:8px;align-items:flex-start;">
						<div style="flex:1;">
							${details_short}
							${je_list.length > 0 ? `<div style="font-size:11px;margin-top:3px;">📄 ${je_list.map(j => {
						if (j.startsWith("PCV:")) {
							const pcv = j.replace("PCV:", "");
							return `<a href="/app/period-closing-voucher/${pcv}" style="color:#6f42c1;">📋${pcv}</a>`;
						}
						return `<a href="/app/journal-entry/${j}">${j}</a>`;
					}).join(", ")}</div>` : ""}
							${step.completed_date ? `<div style="font-size:10px;color:#999;margin-top:2px;">✓ ${step.completed_date}</div>` : ""}
						</div>
						<button class="btn btn-sm btn-outline-success tycw-report" data-step="${step.step_order}" style="font-size:11px;padding:2px 8px;">📊 ${__("Report")}</button>
					</div>`;
			}

			html += `
				<div style="display:flex;align-items:stretch;${indent}">
					<div style="width:36px;display:flex;flex-direction:column;align-items:center;">
						<div style="width:28px;height:28px;border-radius:50%;background:${c.border};color:white;
							display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:bold;
							${is_active ? 'animation:pulse 1.5s infinite;' : ''}">
							${c.icon}
						</div>
						<div style="flex:1;width:2px;background:${c.border};margin:2px 0;"></div>
					</div>
					<div style="flex:1;background:${c.bg};border:1px solid ${c.border};border-radius:6px;
						padding:10px 14px;margin-bottom:2px;
						${font_weight}" data-step="${step.step_order}" class="tycw-step">
						<div style="display:flex;justify-content:space-between;align-items:center;">
							<div>
								<span style="color:${c.color};font-size:13px;">
									${step.period_label}
								</span>
								<span style="color:#999;font-size:11px;margin-left:8px;">${step.taxes_included || ""}</span>
							</div>
							<div style="display:flex;align-items:center;gap:12px;">
								${amount_html}
								${!is_completed ? deadline_html : ""}
							</div>
						</div>
						${completed_summary}
						${is_active && step.details ? `<div style="margin-top:6px;font-size:12px;color:#555;white-space:pre-line;">${frappe.utils.escape_html(step.details)}</div>` : ""}
						${is_active ? `<div style="margin-top:8px;display:flex;gap:6px;" class="tycw-step-actions">` +
							(step.status === "Active" ? `<button class="btn btn-primary btn-sm tycw-calc" data-step="${step.step_order}">${__("Calculate")}</button>` : "") +
							(step.status === "Active" || step.status === "Calculated" ? `<button class="btn btn-info btn-sm tycw-allocate" data-step="${step.step_order}">FIFO Allocate</button>` : "") +
							(step.status === "Calculated" ? `<button class="btn btn-success btn-sm tycw-confirm" data-step="${step.step_order}">${__("Confirm and create")}</button>` : "") +
							(step.status === "Calculated" ? `<button class="btn btn-default btn-sm tycw-recalc" data-step="${step.step_order}">${__("Recalculate")}</button>` : "") +
							`<button class="btn btn-warning btn-sm tycw-report" data-step="${step.step_order}">${__("Report")}</button>
							<button class="btn btn-default btn-sm tycw-skip" data-step="${step.step_order}">${__("Skip")}</button>
						</div>` : ""}
						${step.status === "Skipped" ? `<div style="margin-top:4px;"><button class="btn btn-sm btn-outline-secondary tycw-report" data-step="${step.step_order}" style="font-size:11px;padding:2px 8px;">📊 ${__("Report")}</button></div>` : ""}
					</div>
				</div>`;
		}

		html += '</div>';
		html += `<style>@keyframes pulse { 0%,100%{opacity:1;} 50%{opacity:0.7;} }</style>`;

		const $wrapper = frm.fields_dict.timeline_html.$wrapper;
		$wrapper.html(html);

		// Bind buttons
		$wrapper.find(".tycw-calc").on("click", function(e) {
			e.stopPropagation();
			call_step_action(frm, "calculate_step", $(this).data("step"));
		});
		$wrapper.find(".tycw-confirm").on("click", function(e) {
			e.stopPropagation();
			const step_order = $(this).data("step");
			frappe.confirm(__("Create journal entries for this step?"), () => {
				call_step_action(frm, "complete_step", step_order);
			});
		});
		$wrapper.find(".tycw-recalc").on("click", function(e) {
			e.stopPropagation();
			call_step_action(frm, "calculate_step", $(this).data("step"));
		});
		$wrapper.find(".tycw-skip").on("click", function(e) {
			e.stopPropagation();
			const step_order = $(this).data("step");
			frappe.confirm(__("Skip this step? It will be marked as Skipped."), () => {
				call_step_action(frm, "skip_step", step_order);
			});
		});
		$wrapper.find(".tycw-allocate").on("click", function(e) {
			e.stopPropagation();
			show_fifo_allocation(frm, $(this).data("step"));
		});
		$wrapper.find(".tycw-report").on("click", function(e) {
			e.stopPropagation();
			show_step_monthly_report(frm, $(this).data("step"));
		});
	},


	// ── Current Step Detail ──────────────────────────────

	render_current_step(frm) {
		const steps = frm.doc.steps || [];
		const active = steps.find(s => s.status === "Active" || s.status === "Calculated");

		if (!active) {
			frm.fields_dict.current_step_html && frm.fields_dict.current_step_html.$wrapper.html(
				frm.doc.overall_status === "Completed"
					? `<div style="padding:30px;text-align:center;color:#28a745;font-size:18px;font-weight:bold;">✓ ${__("All steps completed!")}</div>`
					: `<div style="padding:30px;text-align:center;color:#999;">${__("No active step. Go to Timeline tab.")}</div>`
			);
			return;
		}

		let html = `
			<div style="padding:20px;background:#fff;border:2px solid #ffc107;border-radius:8px;">
				<h4 style="margin-bottom:15px;">◉ ${frappe.utils.escape_html(active.period_label)}</h4>
				<div style="display:flex;gap:20px;margin-bottom:15px;">
					<div><strong>${__("Type:")}</strong> ${active.step_type}</div>
					<div><strong>${__("Period:")}</strong> ${active.month_start} — ${active.month_end}</div>
					<div><strong>${__("Taxes:")}</strong> ${frappe.utils.escape_html(active.taxes_included || "")}</div>
					<div><strong>${__("Declaration:")}</strong> ${active.deadline_declaration || "—"}</div>
					<div><strong>${__("Payment:")}</strong> ${active.deadline_payment || "—"}</div>
				</div>
		`;

		if (active.details) {
			html += `<div style="background:#f8f9fa;padding:12px;border-radius:4px;font-family:monospace;font-size:12px;white-space:pre-line;margin-bottom:15px;">
				${frappe.utils.escape_html(active.details)}</div>`;
		}

		if (flt(active.tax_amount) > 0 || active.status === "Calculated") {
			html += `<div style="font-size:18px;font-weight:bold;color:#28a745;margin-bottom:15px;">
				${__("Tax:")} ${format_azn(active.tax_amount)}</div>`;
		}

		html += `</div>`;
		frm.fields_dict.current_step_html && frm.fields_dict.current_step_html.$wrapper.html(html);
	},

	// ── Benefits ─────────────────────────────────────────

	render_benefits(frm) {
		const benefits = frm.doc.detected_benefits || [];
		if (!benefits.length || !frm.fields_dict.benefits_html) return;

		let html = '<div style="display:flex;flex-direction:column;gap:8px;">';
		for (const b of benefits) {
			html += `
				<div style="border-left:4px solid #28a745;background:#f0fdf4;border-radius:4px;padding:10px 14px;">
					<div style="font-weight:bold;color:#155724;">✓ ${frappe.utils.escape_html(b.article)} — ${frappe.utils.escape_html(b.benefit_name)}</div>
					<div style="font-size:12px;color:#555;margin-top:4px;">${frappe.utils.escape_html(b.condition_details || "")}</div>
					${b.law_reference ? `<div style="font-size:11px;color:#4338ca;margin-top:4px;">📖 ${b.law_url ? `<a href="${frappe.utils.escape_html(b.law_url)}" target="_blank" style="color:#4338ca;text-decoration:underline;">${frappe.utils.escape_html(b.law_reference)}</a>` : frappe.utils.escape_html(b.law_reference)}</div>` : ""}
				</div>`;
		}
		html += '</div>';
		frm.fields_dict.benefits_html.$wrapper.html(html);
	},

	// ── Summary ──────────────────────────────────────────

	render_summary(frm) {
		const steps = frm.doc.steps || [];
		if (!steps.length || !frm.fields_dict.summary_html) return;

		const completed = steps.filter(s => s.status === "Completed");
		const skipped = steps.filter(s => s.status === "Skipped");
		const pending = steps.filter(s => s.status === "Pending" || s.status === "Active");

		let html = `
			<div style="display:flex;gap:15px;margin-bottom:15px;">
				<div style="flex:1;padding:15px;background:#d4edda;border-radius:6px;text-align:center;">
					<div style="font-size:24px;font-weight:bold;color:#155724;">${completed.length}</div>
					<div style="color:#155724;">${__("Completed")}</div>
				</div>
				<div style="flex:1;padding:15px;background:#e2e3e5;border-radius:6px;text-align:center;">
					<div style="font-size:24px;font-weight:bold;color:#383d41;">${skipped.length}</div>
					<div style="color:#383d41;">${__("Skipped")}</div>
				</div>
				<div style="flex:1;padding:15px;background:#fff3cd;border-radius:6px;text-align:center;">
					<div style="font-size:24px;font-weight:bold;color:#856404;">${pending.length}</div>
					<div style="color:#856404;">${__("Pending")}</div>
				</div>
			</div>
		`;

		if (completed.length > 0) {
			html += `<table class="table table-sm table-bordered" style="font-size:12px;">
				<thead style="background:#2c3e50;color:white;">
					<tr><th>${__("Period")}</th><th>${__("Taxes")}</th><th style="text-align:right;">${__("Amount")}</th><th>${__("JE")}</th><th>${__("Date")}</th></tr>
				</thead><tbody>`;
			for (const s of completed) {
				const jes = (s.journal_entries || "").split(",").map(j => {
					j = j.trim();
					return j ? `<a href="/app/journal-entry/${j}">${j}</a>` : "";
				}).filter(Boolean).join(", ");
				html += `<tr>
					<td>${frappe.utils.escape_html(s.period_label)}</td>
					<td>${frappe.utils.escape_html(s.taxes_included || "")}</td>
					<td style="text-align:right;font-weight:bold;">${format_azn(s.tax_amount)}</td>
					<td>${jes}</td>
					<td>${s.completed_date || ""}</td>
				</tr>`;
			}
			html += `</tbody></table>`;
		}

		frm.fields_dict.summary_html.$wrapper.html(html);
	}
});

function format_azn(val) {
	return (parseFloat(val) || 0).toLocaleString("az-AZ", {
		minimumFractionDigits: 2, maximumFractionDigits: 2
	}) + " AZN";
}

function flt(val) {
	return parseFloat(val) || 0;
}

function show_step_monthly_report(frm, step_order) {
	frappe.call({
		method: "taxes_az.taxes_az.doctype.tax_year_closing_wizard.tax_year_closing_wizard.get_step_report",
		args: { name: frm.doc.name, step_order: step_order },
		freeze: true,
		freeze_message: __("Loading report..."),
		callback(r) {
			if (!r || !r.message) return;
			const d = r.message;
			const f = (v) => (parseFloat(v) || 0).toLocaleString("az-AZ", {minimumFractionDigits:2, maximumFractionDigits:2});

			let html = `<div style="font-family:-apple-system,sans-serif;font-size:13px;">`;

			// Header
			html += `<div style="background:#2c3e50;color:white;padding:14px;border-radius:6px;margin-bottom:12px;display:flex;justify-content:space-between;">
				<div><strong style="font-size:16px;">${d.period}</strong><br>${d.from} — ${d.to}</div>
				<div style="text-align:right;">${__("Declaration:")} ${d.deadline_declaration || "—"}<br>${__("Payment:")} ${d.deadline_payment || "—"}</div>
			</div>`;

			// Cash flow
			html += `<div style="display:flex;gap:10px;margin-bottom:12px;">
				<div style="flex:1;padding:12px;background:#d4edda;border-radius:6px;text-align:center;">
					<div style="font-size:11px;color:#155724;">${__("Cash in (PE+226)")}</div>
					<div style="font-size:18px;font-weight:bold;color:#155724;">${f(d.total_cash_in)} AZN</div>
				</div>
				<div style="flex:1;padding:12px;background:#f8d7da;border-radius:6px;text-align:center;">
					<div style="font-size:11px;color:#721c24;">${__("Cash out")}</div>
					<div style="font-size:18px;font-weight:bold;color:#721c24;">${f(d.payments_made)} AZN</div>
				</div>
				<div style="flex:1;padding:12px;background:#cce5ff;border-radius:6px;text-align:center;">
					<div style="font-size:11px;color:#004085;">ƏDV (226)</div>
					<div style="font-size:18px;font-weight:bold;color:#004085;">${f(d.vat_226_received)} AZN</div>
				</div>
			</div>`;

			// Income table
			if ((d.income || []).length > 0) {
				html += `<h5>${__("Income")}</h5><table class="table table-sm table-bordered">
					<thead style="background:#28a745;color:white;"><tr><th>${__("Account")}</th><th>${__("Name")}</th><th style="text-align:right;">${__("Amount")}</th></tr></thead><tbody>`;
				for (const i of d.income) {
					html += `<tr><td>${i.account}</td><td>${i.name}</td><td style="text-align:right;">${f(i.amount)}</td></tr>`;
				}
				html += `<tr style="font-weight:bold;background:#d4edda;"><td colspan="2">${__("Total income")}</td><td style="text-align:right;">${f(d.total_income)} AZN</td></tr>`;
				html += `</tbody></table>`;
			}

			// Expense table
			if ((d.expenses || []).length > 0) {
				html += `<h5>${__("Expenses")}</h5><table class="table table-sm table-bordered">
					<thead style="background:#dc3545;color:white;"><tr><th>${__("Account")}</th><th>${__("Name")}</th><th style="text-align:right;">${__("Amount")}</th></tr></thead><tbody>`;
				for (const e of d.expenses) {
					html += `<tr><td>${e.account}</td><td>${e.name}</td><td style="text-align:right;">${f(e.amount)}</td></tr>`;
				}
				html += `<tr style="font-weight:bold;background:#f8d7da;"><td colspan="2">${__("Total expense")}</td><td style="text-align:right;">${f(d.total_expense)} AZN</td></tr>`;
				html += `</tbody></table>`;
			}

			// Profit
			const profit_color = d.net_profit >= 0 ? "#28a745" : "#dc3545";
			html += `<div style="padding:10px;background:#f8f9fa;border-radius:4px;margin-bottom:12px;">
				<strong>${__("Net profit/loss:")}</strong>
				<span style="font-size:16px;font-weight:bold;color:${profit_color};margin-left:10px;">${f(d.net_profit)} AZN</span>
			</div>`;

			// VAT
			html += `<h5>ƏDV</h5><table class="table table-sm table-bordered">
				<tr><td>ƏDV çıxış (521.3)</td><td style="text-align:right;">${f(d.vat_output)}</td></tr>
				<tr><td>ƏDV daxil (226)</td><td style="text-align:right;">${f(d.vat_input)}</td></tr>
				<tr style="font-weight:bold;"><td>Nett ƏDV</td><td style="text-align:right;">${f(d.vat_net)}</td></tr>
			</table>`;

			// Payroll
			if (d.payroll) {
				html += `<h5>${__("Payroll")}</h5><table class="table table-sm table-bordered">
					<tr><td>${__("Employee count")}</td><td style="text-align:right;">${d.payroll.count}</td></tr>
					<tr><td>${__("Gross salary")}</td><td style="text-align:right;">${f(d.payroll.gross)}</td></tr>
					<tr><td>${__("Deductions")}</td><td style="text-align:right;">${f(d.payroll.deductions)}</td></tr>
					<tr><td>${__("Net salary")}</td><td style="text-align:right;">${f(d.payroll.net)}</td></tr>
				</table>`;
			}

			// FIFO status
			if ((d.fifo_entries || []).length > 0) {
				html += `<h5>FIFO Allocations</h5>`;
				for (const j of d.fifo_entries) {
					html += `<a href="/app/journal-entry/${j.name}">${j.name}</a> (${f(j.amount)}) `;
				}
			} else {
				html += `<div style="padding:8px;background:#fff3cd;border-radius:4px;color:#856404;">
					${__("FIFO allocation not done yet. Click the FIFO Allocate button.")}</div>`;
			}

			// Step JEs + PCV
			if ((d.step_jes || []).length > 0) {
				html += `<h5 style="margin-top:10px;">${__("Created documents")}</h5>`;
				for (const j of d.step_jes) {
					if (j.startsWith("PCV:")) {
						const pcv_name = j.replace("PCV:", "");
						html += `<div style="margin:4px 0;"><a href="/app/period-closing-voucher/${pcv_name}" style="color:#6f42c1;font-weight:bold;">📋 ${pcv_name} (Period Closing Voucher)</a></div>`;
					} else {
						html += `<a href="/app/journal-entry/${j}">${j}</a> `;
					}
				}
			}

			html += `</div>`;

			new frappe.ui.Dialog({
				title: `📊 ${d.period} — ${__("Report")}`,
				size: "extra-large",
				fields: [{ fieldtype: "HTML", options: html }],
				secondary_action_label: __("Close"),
			}).show();
		}
	});
}

function show_fifo_allocation(frm, step_order) {
	// First preview
	frappe.call({
		method: "taxes_az.taxes_az.doctype.tax_year_closing_wizard.tax_year_closing_wizard.preview_allocation",
		args: { name: frm.doc.name, step_order: step_order },
		freeze: true,
		freeze_message: __("Analyzing FIFO allocation..."),
		callback(r) {
			if (!r || !r.message) return;
			const data = r.message;

			if (data.error) {
				frappe.msgprint({ message: data.error, indicator: "red" });
				return;
			}

			const allocs = data.allocations || [];
			let total_vat = 0, total_rev = 0;
			allocs.forEach(a => { total_vat += a.vat_transfer; total_rev += a.revenue_transfer; });

			let html = `<div style="font-family:-apple-system,sans-serif;">`;

			// Summary
			html += `<div style="display:flex;gap:12px;margin-bottom:14px;">
				<div style="flex:1;padding:12px;background:#d4edda;border-radius:6px;text-align:center;">
					<div style="font-size:18px;font-weight:bold;color:#155724;">${allocs.length}</div>
					<div style="color:#155724;font-size:12px;">${__("Allocation")}</div>
				</div>
				<div style="flex:1;padding:12px;background:#cce5ff;border-radius:6px;text-align:center;">
					<div style="font-size:18px;font-weight:bold;color:#004085;">${format_azn(total_vat)}</div>
					<div style="color:#004085;font-size:12px;">ƏDV → 521.3</div>
				</div>
				<div style="flex:1;padding:12px;background:#fff3cd;border-radius:6px;text-align:center;">
					<div style="font-size:18px;font-weight:bold;color:#856404;">${format_azn(total_rev)}</div>
					<div style="color:#856404;font-size:12px;">Gəlir → 601</div>
				</div>
			</div>`;

			// Allocation table
			if (allocs.length > 0) {
				html += `<table class="table table-sm table-bordered" style="font-size:12px;">
					<thead style="background:#2c3e50;color:white;">
						<tr><th>${__("Invoice")}</th><th>${__("Customer")}</th><th>${__("Payment date")}</th>
						<th style="text-align:right;">${__("Allocation")}</th><th style="text-align:center;">%</th>
						<th style="text-align:right;">ƏDV</th><th style="text-align:right;">Gəlir</th></tr>
					</thead><tbody>`;
				for (const a of allocs) {
					html += `<tr>
						<td><a href="/app/sales-invoice/${a.invoice}">${a.invoice}</a></td>
						<td style="font-size:11px;">${(a.customer || "").substring(0,25)}</td>
						<td>${a.payment_date}</td>
						<td style="text-align:right;">${format_azn(a.allocated)}</td>
						<td style="text-align:center;">${(a.ratio*100).toFixed(0)}%</td>
						<td style="text-align:right;color:#004085;">${format_azn(a.vat_transfer)}</td>
						<td style="text-align:right;color:#856404;">${format_azn(a.revenue_transfer)}</td>
					</tr>`;
				}
				html += `</tbody></table>`;
			} else {
				html += `<div style="padding:15px;text-align:center;color:#999;">
					${__("No payments found for allocation in this period.")}</div>`;
			}

			html += `</div>`;

			const dialog = new frappe.ui.Dialog({
				title: __("FIFO Cash Allocation — Preview"),
				size: "extra-large",
				fields: [{ fieldtype: "HTML", options: html }],
				primary_action_label: allocs.length > 0 ? __("Confirm and create") : null,
				primary_action() {
					dialog.hide();
					frappe.call({
						method: "taxes_az.taxes_az.doctype.tax_year_closing_wizard.tax_year_closing_wizard.execute_allocation",
						args: { name: frm.doc.name, step_order: step_order },
						freeze: true,
						freeze_message: __("Creating allocation entries..."),
						callback(r2) {
							if (r2 && r2.message) {
								const res = r2.message;
								frappe.msgprint({
									title: __("FIFO Allocation completed"),
									message: `<div style="font-size:14px;">
										<p>✓ <strong>${res.count}</strong> ${__("Journal Entries created")}</p>
										<p>${__("VAT recognition:")} <strong>${format_azn(res.total_vat)}</strong> (245.1 → 521.3)</p>
										<p>${__("Revenue recognition:")} <strong>${format_azn(res.total_revenue)}</strong> (542 → 601)</p>
										${(res.created_jes || []).map(j => `<a href="/app/journal-entry/${j}">${j}</a>`).join(", ")}
									</div>`,
									indicator: "green",
									wide: true,
								});
							}
							window.location.reload();
						}
					});
				},
				secondary_action_label: __("Close"),
			});
			dialog.show();
		}
	});
}

// ── Check SI Accounts Before Closing ─────────────────

function check_and_fix_before_closing(frm, on_continue) {
	frappe.call({
		method: "taxes_az.taxes_az.doctype.tax_year_closing_wizard.tax_year_closing_wizard.check_si_accounts",
		args: { name: frm.doc.name },
		callback(r) {
			if (!r || !r.message) { on_continue(); return; }
			const data = r.message;

			if (!data.needs_fix) {
				on_continue();
				return;
			}

			// Show fix dialog
			const wrong = data.wrong || [];
			let html = `<div style="font-family:-apple-system,sans-serif;">
				<div style="padding:10px;background:#fff3cd;border-radius:6px;margin-bottom:12px;">
					${__("{0} Sales Invoices still on old accounts (521.3/601). For cash method they must be moved to 245.1/542.", [wrong.length])}
				</div>
				<table class="table table-sm table-bordered" style="font-size:12px;">
					<thead style="background:#2c3e50;color:white;">
						<tr><th>${__("Invoice")}</th><th>${__("Date")}</th><th style="text-align:right;">ƏDV</th><th style="text-align:right;">${__("Total")}</th></tr>
					</thead><tbody>`;

			for (const w of wrong.slice(0, 20)) {
				html += `<tr>
					<td><a href="/app/sales-invoice/${w.invoice}">${w.invoice}</a></td>
					<td>${w.date}</td>
					<td style="text-align:right;">${format_azn(w.vat)}</td>
					<td style="text-align:right;">${format_azn(w.total)}</td>
				</tr>`;
			}
			if (wrong.length > 20) {
				html += `<tr><td colspan="4">... ${__("and more")} ${wrong.length - 20}</td></tr>`;
			}
			html += `</tbody></table></div>`;

			const dlg = new frappe.ui.Dialog({
				title: __("Invoice account correction required"),
				size: "large",
				fields: [{ fieldtype: "HTML", options: html }],
				primary_action_label: __("Fix and continue"),
				primary_action() {
					dlg.hide();
					frappe.call({
						method: "taxes_az.taxes_az.doctype.tax_year_closing_wizard.tax_year_closing_wizard.fix_si_accounts",
						args: { name: frm.doc.name },
						freeze: true,
						freeze_message: __("Fixing invoices..."),
						callback(r2) {
							if (r2 && r2.message) {
								frappe.show_alert({
									message: __("{0} invoices fixed", [r2.message.fixed]),
									indicator: "green"
								});
							}
							on_continue();
						}
					});
				},
				secondary_action_label: __("Continue without fixing"),
				secondary_action() {
					dlg.hide();
					on_continue();
				}
			});
			dlg.show();
		}
	});
}

// ── Run All Steps Sequentially ───────────────────────

function run_all_steps_sequentially(frm) {
	const steps = (frm.doc.steps || []).filter(s => s.status !== "Completed" && s.status !== "Skipped");
	if (!steps.length) {
		frappe.msgprint(__("All steps already completed."));
		return;
	}

	// Create progress dialog
	const dlg = new frappe.ui.Dialog({
		title: __("Close all periods"),
		size: "large",
		static: true,
		fields: [{ fieldtype: "HTML", fieldname: "progress_area" }],
		secondary_action_label: __("Stop"),
		secondary_action() {
			dlg._stopped = true;
			dlg.hide();
			window.location.reload();
		}
	});
	dlg._stopped = false;
	dlg.show();

	const $area = dlg.fields_dict.progress_area.$wrapper;

	function render_progress(current_idx, total, current_step, phase, error) {
		const pct = Math.round((current_idx / total) * 100);

		let rows = "";
		const all_steps = frm.doc.steps || [];
		for (const st of all_steps) {
			let icon, bg, text_color;
			if (st.status === "Completed") {
				icon = "✓"; bg = "#d4edda"; text_color = "#155724";
			} else if (st.status === "Skipped") {
				icon = "—"; bg = "#e2e3e5"; text_color = "#383d41";
			} else if (st.step_order === (current_step ? current_step.step_order : -1)) {
				if (error) {
					icon = "✗"; bg = "#f8d7da"; text_color = "#721c24";
				} else {
					icon = "⟳"; bg = "#fff3cd"; text_color = "#856404";
				}
			} else {
				icon = "○"; bg = "#f8f9fa"; text_color = "#6c757d";
			}

			const is_current = current_step && st.step_order === current_step.step_order;
			const phase_text = is_current && phase ? ` — <em>${phase}</em>` : "";
			const amount_text = st.status === "Completed" && flt(st.tax_amount) > 0
				? `<span style="color:#28a745;font-weight:bold;margin-left:8px;">${format_azn(st.tax_amount)}</span>` : "";
			const error_text = is_current && error
				? `<div style="color:#dc3545;font-size:11px;margin-top:2px;">${error}</div>` : "";

			rows += `<div style="display:flex;align-items:center;gap:8px;padding:5px 10px;background:${bg};
				border-radius:4px;margin-bottom:2px;${is_current ? 'border-left:4px solid '+text_color+';' : ''}">
				<span style="font-size:14px;color:${text_color};width:20px;text-align:center;
					${is_current && !error ? 'animation:spin 1s linear infinite;' : ''}">${icon}</span>
				<span style="color:${text_color};font-size:12px;flex:1;">${st.period_label}${phase_text}</span>
				${amount_text}
			</div>${error_text}`;
		}

		$area.html(`
			<style>@keyframes spin { from{transform:rotate(0deg)} to{transform:rotate(360deg)} }</style>
			<div style="margin-bottom:12px;">
				<div style="display:flex;justify-content:space-between;margin-bottom:4px;">
					<span style="font-weight:bold;">${current_step ? current_step.period_label : __("Completed")}</span>
					<span style="font-weight:bold;">${pct}%</span>
				</div>
				<div style="background:#e9ecef;border-radius:8px;overflow:hidden;height:20px;">
					<div style="width:${pct}%;height:100%;background:linear-gradient(90deg,#28a745,#20c997);
						border-radius:8px;transition:width 0.5s ease;"></div>
				</div>
			</div>
			<div style="max-height:400px;overflow-y:auto;">${rows}</div>
		`);
	}

	// Sequential processing
	let step_idx = 0;
	const pending_steps = steps.slice();

	async function process_next() {
		if (dlg._stopped) return;
		if (step_idx >= pending_steps.length) {
			// All done!
			render_progress(pending_steps.length, pending_steps.length, null, null, null);
			$area.prepend(`<div style="padding:14px;background:#28a745;color:white;border-radius:6px;
				margin-bottom:12px;text-align:center;font-size:16px;font-weight:bold;">
				✓ ${__("All steps completed successfully!")}</div>`);
			dlg.set_secondary_action_label(__("Close"));
			dlg.set_secondary_action(() => { dlg.hide(); window.location.reload(); });
			return;
		}

		const step = pending_steps[step_idx];
		const total = pending_steps.length;

		try {
			// Phase 1: Calculate
			render_progress(step_idx, total, step, __("Calculating..."), null);
			await call_step_async("calculate_step", frm.doc.name, step.step_order);

			if (dlg._stopped) return;

			// Phase 2: Complete (includes FIFO for kassa, VAT for hesablama)
			render_progress(step_idx, total, step, __("Confirming..."), null);
			const result = await call_step_async("complete_step", frm.doc.name, step.step_order);

			// Update local step data
			step.status = "Completed";
			if (result && result.step_data) {
				step.tax_amount = result.step_data.tax_amount;
				step.details = result.step_data.details;
				step.journal_entries = result.step_data.journal_entries;
			}

			step_idx++;
			// Small delay for visual effect
			setTimeout(process_next, 300);

		} catch (err) {
			const msg = (err && err.message) || String(err) || "Unknown error";
			render_progress(step_idx, total, step, null, msg);
			$area.prepend(`<div style="padding:10px;background:#f8d7da;color:#721c24;border-radius:6px;margin-bottom:12px;">
				✗ ${__("Error:")} ${step.period_label} — ${frappe.utils.escape_html(msg)}.
				${__("Previous steps have been saved.")}</div>`);
			dlg.set_secondary_action_label(__("Close"));
			dlg.set_secondary_action(() => { dlg.hide(); window.location.reload(); });
		}
	}

	// Reload doc first to get fresh data
	frm.reload_doc().then(() => {
		process_next();
	});
}

function call_step_async(action, name, step_order) {
	return new Promise((resolve, reject) => {
		frappe.call({
			method: `taxes_az.taxes_az.doctype.tax_year_closing_wizard.tax_year_closing_wizard.${action}`,
			args: { name: name, step_order: step_order },
			async: true,
			callback(r) {
				if (r && r.message) resolve(r.message);
				else resolve({});
			},
			error(err) {
				reject(err);
			}
		});
	});
}

function call_step_action(frm, action, step_order) {
	const labels = {
		"calculate_step": __("Calculating..."),
		"complete_step": __("Creating journal entries..."),
		"skip_step": __("Skipping..."),
	};
	frappe.call({
		method: `taxes_az.taxes_az.doctype.tax_year_closing_wizard.tax_year_closing_wizard.${action}`,
		args: { name: frm.doc.name, step_order: step_order },
		freeze: true,
		freeze_message: __(labels[action] || "Processing..."),
		callback(r) {
			if (action === "complete_step" && r && r.message) {
				show_step_report(r.message, () => window.location.reload());
			} else {
				window.location.reload();
			}
		},
		error() { window.location.reload(); }
	});
}

function show_step_report(data, on_close) {
	const s = data.step_data || {};
	const jes = (s.journal_entries || "").split(",").filter(j => j.trim());

	let html = `<div style="font-family: -apple-system, sans-serif;">`;

	// Header
	html += `<div style="padding:14px;background:#28a745;color:white;border-radius:6px;margin-bottom:14px;text-align:center;">
		<div style="font-size:18px;font-weight:bold;">✓ ${frappe.utils.escape_html(s.period_label || "")}</div>
		<div style="font-size:13px;margin-top:4px;">${__("Step completed successfully")}</div>
	</div>`;

	// Details
	html += `<table class="table table-bordered" style="font-size:13px;">
		<tr><td style="width:40%;"><strong>${__("Period")}</strong></td><td>${s.period_label || ""}</td></tr>
		<tr><td><strong>${__("Type")}</strong></td><td>${s.step_type || ""}</td></tr>
		<tr><td><strong>${__("Date range")}</strong></td><td>${s.month_start || ""} — ${s.month_end || ""}</td></tr>
		<tr><td><strong>${__("Taxes")}</strong></td><td>${frappe.utils.escape_html(s.taxes_included || "")}</td></tr>
		<tr><td><strong>${__("Declaration deadline")}</strong></td><td>${s.deadline_declaration || "—"}</td></tr>
		<tr><td><strong>${__("Payment deadline")}</strong></td><td>${s.deadline_payment || "—"}</td></tr>
		<tr style="background:#d4edda;"><td><strong>${__("Tax amount")}</strong></td>
			<td style="font-size:16px;font-weight:bold;">${format_azn(s.tax_amount)}</td></tr>
	</table>`;

	// Calculation details
	if (s.details) {
		html += `<div style="background:#f8f9fa;padding:10px;border-radius:4px;font-family:monospace;font-size:12px;white-space:pre-line;margin-bottom:14px;">
			${frappe.utils.escape_html(s.details)}</div>`;
	}

	// Journal Entries
	if (jes.length > 0) {
		html += `<h5>${__("Created documents")}</h5>
			<table class="table table-sm table-bordered" style="font-size:13px;">
			<thead style="background:#343a40;color:white;">
				<tr><th>${__("Journal Entry")}</th><th>${__("Link")}</th></tr>
			</thead><tbody>`;
		for (const je of jes) {
			const name = je.trim();
			html += `<tr>
				<td>${name}</td>
				<td><a href="/app/journal-entry/${name}" target="_blank" style="color:#007bff;">
					${__("Click to open")} →</a></td>
			</tr>`;
		}
		html += `</tbody></table>`;
	} else {
		html += `<div style="padding:10px;background:#fff3cd;border-radius:4px;font-size:12px;color:#856404;">
			${__("No journal entries created (amount = 0 or data collection only)")}</div>`;
	}

	// Next step info
	if (data.next_step) {
		html += `<div style="margin-top:14px;padding:10px;background:#e3f2fd;border-left:4px solid #2196f3;border-radius:4px;">
			<strong>${__("Next step:")}</strong> ${frappe.utils.escape_html(data.next_step)}
		</div>`;
	}

	html += `</div>`;

	const dialog = frappe.msgprint({
		title: __("Step completed"),
		message: html,
		indicator: "green",
		wide: true,
		primary_action: {
			label: __("Continue"),
			action() { dialog.hide(); if (on_close) on_close(); }
		}
	});
}
